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

React Native加载自定义ONNX模型失败,请求问题排查

问题分析与修复方案

1. ONNX Runtime 依赖配置不全

Expo 托管项目里,onnxruntime-react-native 不能直接用默认安装流程,得补全配置:

  • 先装全依赖:
    npm install onnxruntime-react-native expo-asset
    
  • 要是用的 Expo SDK 49 及以上,必须跑预构建,不然原生模块没法运行:
    npx expo prebuild
    
  • 把模型目录加到 app.json 的 assets 列表里,确保打包时能包含:
    "assets": ["./assets/model/"]
    

2. 模型加载路径写错了

你代码里用 asset.localUri 可能有问题,换 asset.uri 试试,同时确保模型下载完成:
修改加载逻辑:

const startOnnxRuntimeSession  = async () => {
  try {
    const modelAsset = require('./assets/model/best.onnx');
    const asset = Asset.fromModule(modelAsset);
    await asset.downloadAsync(); // 强制完成下载
    
    const session = await InferenceSession.create(asset.uri);
    setOnnxSession(session);
    console.log('ONNX session started successfully');

    const modelInfo = await session.getInfo();
    console.log(modelInfo);
  } catch(error){
    console.error('Error while starting the ONNX session:', error);
  }
};

另外先确认模型本身没问题——用桌面版 ONNX Runtime 试试能不能加载这个 best.onnx,排除模型损坏的情况。

3. 权限没搞定

你代码里用到 hasPermission 但没申请权限的逻辑,得先申请文件读取权限:

  • 装权限相关依赖:
    npm install expo-permissions expo-file-system
    
  • 加权限申请代码:
    import * as Permissions from 'expo-permissions';
    const [hasPermission, setHasPermission] = useState(false);
    
    useEffect(() => {
      (async () => {
        const { status } = await Permissions.askAsync(Permissions.MEDIA_LIBRARY);
        setHasPermission(status === 'granted');
      })();
    }, []);
    

4. 版本不兼容

检查 onnxruntime-react-native 和 Expo SDK 版本是否匹配:

  • Expo SDK 49+ 建议用 onnxruntime-react-native@1.15.0 及以上版本
  • 版本不对的话,调整一下:
    npm install onnxruntime-react-native@1.15.0
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:53:23