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

使用ethers.js的formatEther报错:Cannot read properties of undefined

问题解决:TypeError: Cannot read properties of undefined (reading 'formatEther')

错误原因

  1. ethers对象未正确导入:未正确引入ethers库时,ethers变量为undefined,无法访问ethers.utils属性。
  2. 方法参数冗余:formatEther仅需传入Wei格式数值,不需要第二个参数"ether"——该方法本身就是用于将Wei转换为Ether的。
  3. 版本适配问题:ethers v6版本中,formatEther已从ethers.utils移至顶层,需直接通过ethers.formatEther调用。

解决步骤

1. 确保正确导入ethers库

  • Node.js CommonJS环境:
const { ethers } = require("ethers");
  • ES模块环境(如React/Vue):
import { ethers } from "ethers";

2. 修正代码

针对ethers v5及以下版本:

// formatEther是同步方法,无需await
const balanceEther = ethers.utils.formatEther(10000000000);

针对ethers v6版本:

const balanceEther = ethers.formatEther(10000000000);

额外说明

  • formatEther为同步方法,原代码中的await属于冗余写法,会引发语法错误(即便包裹在async函数中也无必要)。
  • 传入的数值需为有效的Wei整数,示例中10000000000 Wei等价于0.00001 Ether。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:05:02