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

React应用Web3连接MetaMask时报错Cannot read properties of undefined (reading 'ethereum')

解决方案

报错根本原因

你遇到的报错是代码执行时window对象本身为undefined,因此无法读取其下的ethereum属性,常见于两种场景:React SSR(服务端渲染,比如Next.js项目)、代码在客户端窗口初始化完成前就执行。另外如果是TypeScript项目也可能是全局类型声明缺失导致的编译报错。

修复步骤

  • 第一步:新增window存在性判断,避免服务端/预执行阶段读取不存在的window对象
    将最外层判断逻辑修改为:
    if (typeof window !== 'undefined' && window.ethereum)
    
  • 第二步:如果是Next.js等SSR框架,将这段钱包连接逻辑放到客户端侧执行:可以包裹在useEffect钩子中,或者绑定到「连接钱包」按钮的点击事件回调,确保仅在客户端渲染完成后触发。
  • 第三步:补充TypeScript全局类型声明(仅TS项目需要)
    在项目的全局类型声明文件(通常为src/global.d.ts或react-app-env.d.ts)中添加如下声明,让TS识别window上的MetaMask注入属性:
    interface Window {
      ethereum?: any;
      web3?: any;
    }
    
    如果需要更规范的类型,可以安装@metamask/providers类型包后替换any为对应的官方类型。
  • 第四步:替换废弃API
    window.ethereum.enable()已经被MetaMask官方废弃,建议替换为标准的RPC请求写法:
    await window.ethereum.request({ method: 'eth_requestAccounts' })
    

修改后完整可运行代码

const connectMetaMask = async (dispatch) => {
  if (typeof window !== 'undefined' && window.ethereum) {
    window.web3 = new Web3(window.ethereum);
    try {
      await window.ethereum.request({ method: 'eth_requestAccounts' });
      updateAddress(dispatch);
    } catch (err) {
      alert("Something went wrong.");
    }
  } else if (typeof window !== 'undefined' && window.web3) {
    window.web3 = new Web3(window.web3.currentProvider);
    updateAddress(dispatch);
  } else {
    alert("You have to install MetaMask !");
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:15:03