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

ethers.js连接Metamask报await is only valid in async function错如何解决

问题原因说明

这个错误和JavaScript语法近期变动无关,是await关键字的固有使用规则导致的:await只能在两类场景下正常使用:

  • 被async关键字修饰的异步函数内部
  • 浏览器原生支持的ES模块(即script标签声明type="module")的顶层作用域中
    你参考的示例代码默认省略了外层的async函数封装,直接复制到普通同步上下文运行就会触发该报错。
修复方案

方案1:将逻辑封装到异步函数中调用(兼容性最好)

把连接逻辑包裹在async修饰的函数内再执行即可,示例如下:

async function connectMetaMask() {
  const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
  // 发起账号连接申请
  await provider.send("eth_requestAccounts", []);
  const signer = provider.getSigner();
  console.log("Account:", await signer.getAddress());
}
// 执行连接逻辑
connectMetaMask()

如果需要获取余额,修改逻辑如下:

async function getAccountBalance(smartContractAddress, abi, targetAddress) {
  const provider = new ethers.providers.Web3Provider(window.ethereum);
  await provider.send("eth_requestAccounts", []);
  const contract = new ethers.Contract(smartContractAddress, abi, provider);
  const balance = await contract.getBalance(targetAddress);
  console.log("余额:", balance)
}
// 传入参数调用
getAccountBalance("你的合约地址", "合约ABI", "0x7C76C63DB86bfB5437f7426F4C37b15098Bb81da")

方案2:使用ES模块顶层await

给引入逻辑的script标签添加type="module"属性,即可直接在顶层作用域使用await,无需额外封装异步函数:

<script type="module">
  const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
  await provider.send("eth_requestAccounts", []);
  const signer = provider.getSigner();
  console.log("Account:", await signer.getAddress());
</script>
额外提示

你参考的第二种方案中用到的window.ethereum.enable()方法已经被官方废弃,现在统一推荐使用eth_requestAccounts请求钱包权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:42:01