uni-app nvue页面下mqtt无法使用,总是报错

uni-app nvue页面下mqtt无法使用,总是报错

示例代码:

就是正常的引入mqtt.min.js文件,然后在nvue页面调用它。

操作步骤:

import mqtt from '../../utils/mqtt.js';  
var client;  
onShow: function() {  
  this.connect();  
},  
methods: {  
  // mqtt与服务端连接  
  connect: function() {  
    let hosts = 'wx://' + this.serve.host + ':' + this.serve.wsport + this.serve.path;  
    client = mqtt.connect(  
      hosts,  
      this.options  
    );  
    let that = this;  
    client.on('connect', function() {  
      console.log('连接成功', client)  
      if (client == null) {  
        connect();  
        return  
      }  
      client.subscribe(that.onTopic, {  
        qos: 0  
      }, function(res) {  
        if (!res) {  
          console.log(res, '订阅成功');  
          that.onMessage();  
        }  
      })  
    }).on('reconnect', function(error) {  
      console.log('正在重连......')  
    }).on('error', function(error) {  
      console.log('连接失败...', error)  
    }).on('end', function() {  
      console.log('连接断开')  
    })  
  },  
}

预期结果:

连接成功并且不会报错。

实际结果:

Uncaught TypeError: Illegal invocation   一直报这个错误代码提示。

bug描述:

nvue页面下mqtt无法使用,总是报错

示例图片

项目信息 描述
产品分类 uniapp/App
PC开发环境操作系统 Windows
PC开发环境版本号 10
HBuilderX类型 正式
HBuilderX版本号 3.1.11
手机系统 Android
手机系统版本号 Android 10
手机厂商 华为
手机机型 华为mate30Pro 5G
页面类型 nvue
打包方式 云端
项目创建方式 HBuilderX

更多关于uni-app nvue页面下mqtt无法使用,总是报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app nvue页面下mqtt无法使用,总是报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在nvue页面中使用MQTT确实会遇到一些兼容性问题,主要原因如下:

  1. nvue环境限制:nvue页面运行在原生渲染环境中,与常规vue页面不同,部分JavaScript库可能无法正常使用,特别是依赖浏览器特定API的库。

  2. MQTT库兼容性:mqtt.min.js可能依赖了某些在nvue环境中不可用的Web API,导致"Illegal invocation"错误。

解决方案

  1. 使用uni-app插件市场提供的MQTT插件

    • 推荐使用专门为uni-app优化的MQTT插件,如uni-mqtt
    • 这些插件已经针对nvue环境进行了适配
  2. 使用uni-app的WebSocket API

    // 使用uni.connectSocket替代mqtt.connect
    uni.connectSocket({
      url: 'wx://your-host:port/path',
      success: (res) => {
        console.log('连接成功');
      },
      fail: (err) => {
        console.log('连接失败', err);
      }
    });
    
  3. 检查连接地址格式

    • 确保WebSocket地址格式正确
    • 确认服务端支持WebSocket协议
  4. 权限配置: 在manifest.json中确保已配置网络权限:

    "app-plus": {
      "modules": {
        "Socket": {}
      }
    }
回到顶部