作者:手机用户2502894791 | 来源:互联网 | 2023-06-03 14:34
1.当切换页面的时候,容易与mqtt服务器断开连接,并报错
原因:在onLoad事件中,获取参数的时候使用异步获取,但是在事件里面还使用了这个参数,导致mqtt发布的时候,发了一个空主题,导致连接被断开,然后报异常,错误代码如下
onLoad() {uni.getStorage({key: 'opened_dev',success:res=>{this.phone = res.data.phone;this.dev_id = res.data.dev_id;this.dev_name = res.data.name;this.dev_note = res.data.note;this.regist_time = res.data.regist_time;this.dev_type = res.data.type;this.img_src = res.data.dev_img;}});var globalData = getApp().globalData;globalData.on_mqtt_msg(this.msg_handler);this.send_cmd(0,0);this.timer_id = setInterval(this.get_dht11,3000);},
修改后:
onLoad() {uni.getStorage({key: 'opened_dev',success:res=>{this.phone = res.data.phone;this.dev_id = res.data.dev_id;this.dev_name = res.data.name;this.dev_note = res.data.note;this.regist_time = res.data.regist_time;this.dev_type = res.data.type;this.img_src = res.data.dev_img;var globalData = getApp().globalData;globalData.on_mqtt_msg(this.msg_handler);this.send_cmd(0,0);this.timer_id = setInterval(this.get_dht11,3000);}});},
在pub的时候 加验证
mqtt_pub: function(topic, msg) { if(topic == null || topic == "")return;if(msg == null)return;if (client && is_connected){client.publish(topic, msg);}console.log("mqtt_pub," + "topic=" + topic + ",msg="+msg);
},