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

Expo Go应用中使用NetInfo库报错,求可行解决方案

问题:Expo Go中使用NetInfo库报错NativeModule.RNCNetInfo is null

背景

使用Expo Go测试应用,尝试集成NetInfo库,已执行以下操作:

  • yarn add @react-native-community/netinfo
  • npx pod-install

使用的示例代码:

import NetInfo from "@react-native-community/netinfo";
NetInfo.fetch().then(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});

运行时出现错误:

Error: @react-native-community/netinfo: NativeModule.RNCNetInfo is null. To fix this issue try these steps:

• Run `react-native link @react-native-community/netinfo` in the project root.
• Rebuild and re-run the app.
• If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.
• Check that the library was linked correctly when you used the link command by running through the manual installation instructions in the README.
* If you are getting this error while unit testing you need to mock the native module. Follow the guide in the README.

当前依赖版本(2023年6月):

"@react-native-community/netinfo": "^9.3.10",
"expo": "~48.0.15",
"react-native": "0.71.8",

已知NetInfo属于Expo SDK 48的一部分,但看到有评论称@react-native-community/netinfo无法在Expo Go中使用,寻求解决办法。


解决方案

核心原因

Expo Go内置了NetInfo的实现,但对应是Expo官方封装的版本,而非社区版@react-native-community/netinfo。社区版需要原生链接,而Expo Go不支持自定义原生模块的链接,这是报错的根本原因。

快速修复步骤

  1. 移除社区版NetInfo依赖
    执行卸载命令:

    yarn remove @react-native-community/netinfo
    

    若使用npm则执行:

    npm uninstall @react-native-community/netinfo
    
  2. 使用Expo官方NetInfo
    Expo SDK自带的NetInfo无需额外安装,直接修改导入语句后使用:

    import NetInfo from 'expo-netinfo';
    NetInfo.fetch().then(state => {
      console.log("Connection type", state.type);
      console.log("Is connected?", state.isConnected);
    });
    
  3. 验证功能
    重启Expo Go应用,运行修改后的代码即可正常获取网络状态。

替代方案(需使用社区版时)

如果必须使用社区版@react-native-community/netinfo,则需要:

  • 使用EAS Build构建自定义Expo开发客户端(而非官方Expo Go),自定义客户端支持原生模块链接。
  • 按照社区库文档完成原生配置,通过EAS Build生成专属测试客户端后再进行测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 12:57:08