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

Rust Wasm构造函数报错:Uncaught TypeError: 无法读取undefined的'foo_new'属性

问题:Rust结构体导出到React TypeScript应用时出现Cannot read properties of undefined (reading 'foo_new')错误

重现代码

Rust代码

#[wasm_bindgen]
pub struct Foo {
    contents: u32,
}

#[wasm_bindgen]
impl Foo {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Foo {
        Foo { contents: 0 }
    }

    pub fn get_contents(&self) -> u32 {
        self.contents
    }
}

React TypeScript代码(App.tsx)

function App() {
  let f = new Foo();
  // ...其他代码
}

错误信息

运行应用时触发以下错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'foo_new')

生成的自动代码情况

生成的module.js中Foo类实现

export class Foo {
    static __wrap(ptr) {
        const obj = Object.create(Foo.prototype);
        obj.ptr = ptr;
        return obj;
    }

    __destroy_into_raw() {
        const ptr = this.ptr;
        this.ptr = 0;
        return ptr;
    }

    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_foo_free(ptr);
    }

    constructor() {
        const ret = wasm.foo_new(); // <--- 错误发生在这里
        return Foo.__wrap(ret);
    }

    get_contents() {
        const ret = wasm.__wbg_get_player_id(this.ptr);
        return ret >>> 0;
    }
}

生成的module.d.ts定义

export class Foo {
  free(): void;
  constructor();
  get_contents(): number;
}

问题原因与解决步骤

1. 未正确初始化Wasm模块

错误中的wasm对象为undefined,说明你没有等待Wasm模块加载完成就直接调用了new Foo()。Wasm模块需要异步初始化,不能同步直接使用。

解决代码示例:

import init, { Foo } from './path-to-your-wasm-package';
import { useState, useEffect } from 'react';

function App() {
  const [fooInstance, setFooInstance] = useState<Foo | null>(null);

  useEffect(() => {
    const loadAndInitWasm = async () => {
      // 先完成Wasm模块的初始化
      await init();
      // 初始化完成后再创建Foo实例
      setFooInstance(new Foo());
    };

    loadAndInitWasm();
  }, []);

  return (
    <div>
      {fooInstance ? (
        <p>Foo contents: {fooInstance.get_contents()}</p>
      ) : (
        <p>Loading Wasm...</p>
      )}
    </div>
  );
}

export default App;

2. 编译缓存或代码错误导致导出异常

注意到生成的module.js中,get_contents方法调用了错误的__wbg_get_player_id(应为__wbg_get_contents),这可能是编译缓存或代码拼写问题导致的:

  • 清理项目缓存,重新执行wasm-pack build(或你使用的编译命令)
  • 检查Rust代码中方法名是否拼写正确,确保get_contents没有笔误

3. 确认Wasm模块导入路径正确

确保在App.tsx中导入的Wasm模块路径正确,例如使用wasm-pack build --target web时,生成的文件在pkg目录下,应导入./pkg/your-module-name(替换为实际的模块名称)


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:24:17