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

React Native加载coco-ssd模型时出现fetch未定义错误求助

解决React Native加载@tensorflow-models/coco-ssd时的"Cannot read property 'fetch' of undefined"错误

这个错误的核心原因是TensorFlow.js在React Native环境中未正确初始化网络请求能力,coco-ssd模型加载时调用的fetch方法未被tfjs-react-native正确接管。以下是具体修复方案:

1. 对齐依赖版本兼容性

版本不匹配是常见触发因素,先卸载现有依赖再安装兼容版本:

npm uninstall @tensorflow/tfjs @tensorflow/tfjs-react-native @tensorflow-models/coco-ssd
npm install @tensorflow/tfjs@4.10.0 @tensorflow/tfjs-react-native@1.0.0 @tensorflow-models/coco-ssd@2.2.2

2. 手动绑定React Native的fetch方法

在模型加载流程中,显式为tfjs指定后端并传入全局fetch:
修改loadCocoModel函数如下:

const loadCocoModel = async () => {
  try {
    tf.setBackend('rn-webgl');
    await tf.ready();
    console.log('Tensorflow ready');
    
    const model = await cocossd.load({
      fetchFunc: global.fetch
    });
    console.log('COCO-SSD model loaded.');
    detect(model);
  } catch (error) {
    console.log(error);
  }
};

3. 检查应用权限与网络配置

  • Android:在AndroidManifest.xml中添加网络权限:<uses-permission android:name="android.permission.INTERNET"/>
  • iOS:在Info.plist中配置允许网络请求,若使用默认模型地址(HTTPS)可跳过,若用HTTP需添加NSAppTransportSecurity例外

4. 直接指定模型加载地址(备选方案)

如果上述方法无效,可直接传入模型的完整HTTPS地址:

const model = await cocossd.load('https://tfhub.dev/tensorflow/tfjs-model/coco-ssd/2/default/1');

额外提示

  • 视频目标检测阶段,需将视频帧转换为TensorFlow可处理的张量,可结合tf.node.decodeImage或React Native图像处理工具实现帧提取与格式转换
  • 避免在组件挂载时同步执行模型加载,确保tf.ready()完全完成后再启动模型加载流程

内容的提问来源于stack exchange,提问作者Jasir ullah Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:58:22