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

ReactJS应用使用tfjs tflite时出现TypeError问题求助

React应用加载TFLite模型报错问题

问题详情

  • 在React应用中加载TFLite模型,模型加载代码位于项目的src/components/ModelCamera/components/model.ts文件
  • 删除node_modules并执行npm install更新依赖后,加载任意游戏页面时出现错误:Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.
  • 忽略该错误后应用仍可正常运行,已部署的线上版本也能正常工作
  • 尝试过修改SetWasmPath来解决,但没有效果

可行解决方案

1. 配置Webpack处理WASM文件类型

如果项目用Webpack构建,需确保application/wasm类型被正确处理。在webpack.config.js中添加以下配置:

module.exports = {
  // 其他已有配置...
  module: {
    rules: [
      {
        test: /\.wasm$/,
        type: 'webassembly/async',
      },
    ],
  },
  experiments: {
    asyncWebAssembly: true,
  },
};

2. 锁定tfjs相关包版本

@tensorflow/tfjs和@tensorflow/tfjs-tflite版本不匹配可能导致Wasm加载问题。在package.json中指定兼容的版本号,示例:

{
  "dependencies": {
    "@tensorflow/tfjs": "^4.14.0",
    "@tensorflow/tfjs-tflite": "^0.0.1-alpha.11"
  }
}

修改后重新执行npm install。

3. 修正Wasm文件路径设置

确认Wasm文件的加载路径正确,在模型加载前设置正确的路径:

import * as tf from '@tensorflow/tfjs';

// 指向项目中Wasm文件所在的实际路径,通常在public目录下
tf.setWasmPath(`${window.location.origin}/wasm/`);

4. 调整开发服务器MIME配置

本地开发环境出现问题的话,以Create React App为例,用react-app-rewired修改配置:

  1. 安装依赖:npm install react-app-rewired --save-dev
  2. 在项目根目录创建config-overrides.js:
const path = require('path');

module.exports = function override(config, env) {
  config.module.rules.push({
    test: /\.wasm$/,
    include: path.resolve(__dirname, 'node_modules'),
    type: 'webassembly/async',
  });
  config.experiments = { asyncWebAssembly: true };
  return config;
};
  1. 修改package.json中的启动命令为:"start": "react-app-rewired start"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:45:24