You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用mqtt.js连接React应用与HiveMQ时遇错误求助

React 集成 mqtt.js 连接 HiveMQ Cloud 报错排查与解决

我在React项目中使用mqtt.js包连接HiveMQ Cloud时遇到错误,错误截图如下:
Screenshot of the error

使用的代码如下:

useEffect(() => {
    const options: IClientOptions = {
      protocol: "ws",
      username: "myfirstdevice",
      password: "qweqwe123",
    };

    const client = mqtt.connect('ws://8dedd20fc1164c8e9ce132a8a8359991.s1.eu.hivemq.cloud:8884', options);
    // const client = mqtt.connect(options);
    client.on('connect', function () {
        console.log('Connected');
    });
    client.on('error', function (error) {
        console.log("ERROR", error);
    });
    client.on('message', (topic,message,packet)=>{
        console.log("RECEIVE", topic)
        console.log("RECEIVE", message)
        console.log("RECEIVE", packet)
    });
  }, []);

解决步骤

  • 修正连接协议与地址:HiveMQ Cloud的8884端口为加密WebSocket(WSS)端口,需将连接URL改为wss://8dedd20fc1164c8e9ce132a8a8359991.s1.eu.hivemq.cloud:8884,同时将options中的protocol字段改为"wss"(或直接省略该字段,由URL自动识别)。
  • 补充必要连接配置:显式设置会话清理与自动重连规则,提升连接稳定性:
    const options: IClientOptions = {
      username: "myfirstdevice",
      password: "qweqwe123",
      clean: true,
      reconnectPeriod: 1000, // 断开连接后1秒自动尝试重连
    };
    
  • 清理客户端避免内存泄漏:在组件卸载时关闭MQTT客户端连接,加入useEffect的返回函数:
    useEffect(() => {
      // ... 客户端创建与事件监听代码
    
      return () => {
        if (client?.connected) {
          client.end();
        }
      };
    }, []);
    
  • 验证设备权限:确认HiveMQ Cloud控制台中已注册myfirstdevice设备,密码匹配且未被限制连接权限。

内容的提问来源于stack exchange,提问作者Ichan Rivera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:30:38