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

React Native网络连接检测报错:Cannot read property 'isConnected' of undefined

问题成因与解决方法

这个报错我之前也碰到过,大概率是React Native版本迭代导致的NetInfo模块变更!

从React Native 0.60版本开始,官方把原本内置的NetInfo从核心库中剥离,移交给社区维护的@react-native-community/netinfo包了。如果你还是直接从react-native里导入NetInfo,拿到的会是undefined,调用isConnected自然就会抛出你看到的错误。

另外你提到已经在AndroidManifest.xml加了权限,这步是对的,权限问题不是这次报错的原因~

解决步骤:

  • 安装社区版NetInfo包
    先在项目根目录执行安装命令:

    # npm 方式
    npm install @react-native-community/netinfo --save
    # 或者 yarn 方式
    yarn add @react-native-community/netinfo
    
  • 依赖链接(仅RN 0.59及以下版本需要)
    如果你用的是RN 0.59或更早版本,需要手动链接依赖:

    react-native link @react-native-community/netinfo
    

    RN 0.60+已经支持自动链接,这步可以跳过。

  • 修改导入方式与代码逻辑
    把原来的导入语句:

    import { NetInfo } from 'react-native';
    

    改成:

    import NetInfo from '@react-native-community/netinfo';
    

    同时注意,新版本的NetInfo API有更新,isConnected.fetch()已经被废弃,现在NetInfo.fetch()返回的是一个包含网络状态信息的对象,你的代码需要调整成这样:

    NetInfo.fetch().then(state => {
      if (state.isConnected) {
        this.setState({ loading: true });
        const url = `https://api.apixu.com/v1/current${this.state.cityname}`;
        return fetch(url)
          .then((data) => data.json())
          .then((datajson) => {
            this.setState({ loading: false, fetched: true });
            console.log(this.state.localtime);
          })
          .catch((error) => {
            console.error(error);
          });
      } else {
        Alert.alert("You are offline!");
      }
    });
    
  • 重新构建项目
    最后记得重新运行项目(比如react-native run-android),避免缓存影响变更生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:08:24