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
相关产品推荐
相关产品推荐

