uni-app nvue页面下mqtt无法使用 显示白屏
uni-app nvue页面下mqtt无法使用 显示白屏
示例代码:
// mqtt与服务端连接
connect: function() {
let hosts = 'wx://' + this.serve.host + ':' + this.serve.wsport + this.serve.path;
let that = this;
if (client == null || client.connected == false) {
// console.log(hosts, this.options);
client = mqtt.connect(hosts, this.options);
client.on("connect", () => {
console.log('连接成功')
client.subscribe(that.onTopic, {
qos: 0
}, function(res) {
if (!res) {
console.log(res, '订阅成功');
that.onMessage();
}
})
});
} else {
console.log('mqtt连接失败');
}
client.on('reconnect', function(error) {
console.log('正在重连......')
}).on('error', function(error) {
console.log('连接失败...', error)
that.connect();
}).on('end', function() {
console.log('连接断开')
})
},
操作步骤:
import mqtt from '../../utils/mqtt.js';
var client;
export default {
onShow: function() {
this.connect();
},
methods: {
// mqtt与服务端连接
connect: function() {
let hosts = 'wx://' + this.serve.host + ':' + this.serve.wsport + this.serve.path;
let that = this;
if (client == null || client.connected == false) {
// console.log(hosts, this.options);
client = mqtt.connect(hosts, this.options);
client.on("connect", () => {
console.log('连接成功')
client.subscribe(that.onTopic, {
qos: 0
}, function(res) {
if (!res) {
console.log(res, '订阅成功');
that.onMessage();
}
})
});
} else {
console.log('mqtt连接失败');
}
client.on('reconnect', function(error) {
console.log('正在重连......')
}).on('error', function(error) {
console.log('连接失败...', error)
that.connect();
}).on('end', function() {
console.log('连接断开')
})
},
}
}
预期结果:
正常发消息连接,并且不白屏,一切显示正常。
实际结果:
页面白屏并报错。

bug描述:
进入连接mqtt文件的nvue页面后,页面白屏并报这个错误信息 【Uncaught TypeError: Illegal invocation】
更多关于uni-app nvue页面下mqtt无法使用 显示白屏的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于uni-app nvue页面下mqtt无法使用 显示白屏的实战教程也可以访问 https://www.itying.com/category-93-b0.html
又报这个错误了【reportJSException >>>> exception function:createInstanceContext, exception:white screen cause create instanceContext failed,check js stack ->Uncaught ReferenceError: require is not defined】,我用npm引入的,然后在页面中是这样的【var mqtt = require(‘mqtt’);】,就报上面这个错误了,然后页面白屏,有问题还报错了。
在nvue页面中使用MQTT时出现白屏和"Illegal invocation"错误,通常是由于nvue环境的特殊性导致的兼容性问题。以下是几个关键解决方案:
- 协议问题:nvue中WebSocket协议应使用
ws://而非wx://。将连接地址改为:
let hosts = 'ws://' + this.serve.host + ':' + this.serve.wsport + this.serve.path;
- 引入方式:确保mqtt库支持uni-app环境。建议使用官方推荐的MQTT.js库,并通过npm安装:
npm install mqtt --save
然后在页面中引入:
import mqtt from 'mqtt/dist/mqtt.min.js';
-
生命周期调整:将连接操作从
onShow移至onLoad,确保页面初始化完成后再建立连接。 -
作用域问题:避免使用全局变量
client,改为在组件data中定义:
data() {
return {
client: null
}
}

