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

Next.js+react-three-fiber项目清缓存后3D模型不显示,报WebAssembly错误

问题根因

该报错和项目内自定义的环境变量无关,是项目依赖的3D工具库自带的WebAssembly模块(绝大多数为Draco模型解码器、KTX2纹理解码器)实例化时序异常导致:WASM编译时默认依赖env宿主注入对象,清缓存后静态资源加载顺序波动,env对象还未完成注入就触发了WASM实例化逻辑,因此偶现报错。

解决方案

  • 移除重复依赖:项目同时安装了@react-three/drei和drei两个功能完全一致的同名包,先执行npm uninstall drei或yarn remove drei删除冗余包,避免加载逻辑冲突。
  • 显式指定解码器本地路径:不要使用drei默认的远程CDN解码器路径,将Draco/KTX2解码器资源放入项目public目录下,手动指定加载路径,消除远程资源加载波动影响:
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'

const dracoLoader = new DRACOLoader()
// 解码器文件夹放置于public/draco/路径下
dracoLoader.setDecoderPath('/draco/')
const gltfLoader = new GLTFLoader()
gltfLoader.setDRACOLoader(dracoLoader)
  • 调整Next.js配置适配WASM加载:在next.config.js中添加WASM加载规则,避免打包处理异常:
module.exports = {
  webpack: (config) => {
    config.experiments = {
      ...config.experiments,
      asyncWebAssembly: true,
    }
    config.module.rules.push({
      test: /\.wasm$/,
      type: 'webassembly/async',
    })
    return config
  },
  compress: process.env.NODE_ENV !== 'development'
}
  • 为WASM相关资源配置固定缓存规则:在next.config.js中添加响应头配置,避免清缓存后资源加载时序异常:
module.exports = {
  async headers() {
    return [
      {
        source: '/draco/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable',
          },
        ],
      },
    ]
  },
}
  • 增加加载失败重试兜底:给3D模型加载逻辑添加重试机制,捕获WASM实例化错误后延迟200ms重新触发加载,最多重试3次即可覆盖绝大多数时序异常场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:06:04