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

Expo开发RN应用连接本地Mosquitto遇AMQJS0013E URI错误求助

解决react-native-paho-mqtt的AMQJS0013E URI参数错误问题

核心原因

react-native-paho-mqtt的Client构造函数不支持uri参数,你传入的对象格式不符合库的参数要求,直接导致URI解析失败抛出错误。

分步解决方案

1. 修正Client初始化代码

将原来的对象式参数改为host、port、clientId分开传递的形式,这是该库要求的标准构造方式:

// 错误写法
const client = new Client({
  uri: 'mqtt://127.0.0.1:1883',
  clientId: 'testClient',
});

// 正确写法
const client = new Client('127.0.0.1', 1883, 'testClient');

2. 适配Expo模拟器的网络访问规则

不同模拟器访问本机服务器的地址不同,需针对性调整:

  • iOS模拟器:直接用127.0.0.1即可访问本机Mosquitto服务器
  • Android模拟器:需替换为10.0.2.2(Android模拟器内置的本机回环地址映射),或者你的本机局域网IP(比如192.168.1.100)

3. 确保Mosquitto服务器允许外部连接

修改本地Mosquitto的配置文件(通常名为mosquitto.conf):

  • 添加或修改监听配置:listener 1883 0.0.0.0(允许所有IP访问1883端口)
  • 若未配置身份验证,添加allow_anonymous true允许匿名连接;若已配置,确保客户端传入正确的用户名密码

修正后的完整组件代码

import React, { useEffect, useState } from 'react';
import { Text, View, Platform } from 'react-native';
import { Client } from 'react-native-paho-mqtt';

const MQTTComponent = () => {
  const [message, setMessage] = useState('');

  useEffect(() => {
    // 根据自动识别模拟器类型选择对应主机地址
    const host = Platform.OS === 'android' ? '10.0.2.2' : '127.0.0.1';
    // 给clientId加随机后缀,避免同一ID重复连接导致断开
    const client = new Client(host, 1883, `testClient_${Math.random().toString(36).substr(2, 9)}`);

    const handleMessage = (msg) => {
      console.log(`Received message on ${msg.destinationName}: ${msg.payloadString}`);
      setMessage(msg.payloadString);
    };

    client.onMessageArrived = handleMessage;

    client.connect()
      .then(() => {
        console.log('Connected to MQTT server');
        client.subscribe('topic');
      })
      .catch(err => console.error('Connection error:', err));

    return () => {
      client.unsubscribe('topic');
      client.disconnect();
    };
  }, []);

  return (
    <View style={{ padding: 20 }}>
      <Text>Received MQTT Message: {message || 'Waiting...'}</Text>
    </View>
  );
};

export default MQTTComponent;

额外注意点

  • 给clientId添加随机后缀,避免同一客户端ID重复连接导致前序连接被强制断开
  • 确认Expo应用具备网络权限(默认已开启,自定义配置时需检查)
  • 可用MQTTX测试对应地址的连通性,先确认服务器本身运行正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:17:41