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

React Native使用Expo无法连接智能手机问题求助

WSL Ubuntu下Expo Tunnel连接Metro断开的解决办法

问题场景

在Windows 10的WSL Ubuntu环境开发React Native新项目,同一网络下用expo start --tunnel在手机端通过Expo访问,运行一段时间后出现Metro连接失败错误,错误信息如下:

Cannot connect to Metro.

Try the following to fix the issue:

Ensure that Metro is running and available on the same network

Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices

If you're on a physical device connected to the same machine, run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device

If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:8081
URL: q3-fmi.anonymous.sistema-mobile-fluxo.exp.direct:80

Error: null at node_modules/metro-runtime/src/modules/vendor/eventemitter3.js:195:15 in emit at node_modules/metro-runtime/src/modules/HMRClient.js:50:6 in _ws.onerror at node_modules/react-native/Libraries/WebSocket/WebSocket.js:271:8 in _eventEmitter.addListener$argument_1 at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:150:10 in EventEmitter#emit

解决步骤

1. 修复WSL端口映射与防火墙

WSL的网络隔离可能导致Metro端口无法被外部设备访问:

  • 以管理员身份打开Windows命令提示符,执行端口映射(替换<WSL_IP>为Ubuntu终端ip addr show eth0输出的172开头IP):
    netsh interface portproxy add v4tov4 listenport=8081 listenaddress=0.0.0.0 connectport=8081 connectaddress=<WSL_IP>
    
  • 允许Windows防火墙通过8081端口:
    netsh advfirewall firewall add rule name="Metro Server" dir=in action=allow protocol=TCP localport=8081
    

2. 改用Local模式替代Tunnel模式

同一网络下无需依赖Expo中转服务,Local模式更稳定:

  • 启动Expo时执行:
    expo start --local
    
  • 手机端扫描终端二维码,若无法识别,手动在Dev设置中配置Windows主机的局域网IP+8081端口(如192.168.1.100:8081)

3. 调整Metro的WebSocket超时配置

新建或修改项目根目录的metro.config.js,延长连接超时:

const { getDefaultConfig } = require('@expo/metro-config');

const config = getDefaultConfig(__dirname);

config.server = {
  enhanceMiddleware: (middleware) => {
    return (req, res, next) => {
      res.setHeader('Connection', 'keep-alive');
      res.setHeader('Keep-Alive', 'timeout=600');
      return middleware(req, res, next);
    };
  },
};

module.exports = config;

修改后重启Metro服务。

4. 维持WSL网络活跃性

  • 关闭Windows快速启动功能,避免WSL网络休眠
  • 若仍出现断开,在Windows命令提示符执行wsl --shutdown后重启WSL,再重新启动项目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:24:04