使用ethers.js的formatEther报错:Cannot read properties of undefined
问题解决:TypeError: Cannot read properties of undefined (reading 'formatEther')
错误原因
- ethers对象未正确导入:未正确引入ethers库时,
ethers变量为undefined,无法访问ethers.utils属性。 - 方法参数冗余:
formatEther仅需传入Wei格式数值,不需要第二个参数"ether"——该方法本身就是用于将Wei转换为Ether的。 - 版本适配问题: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整数,示例中
10000000000Wei等价于0.00001Ether。
内容的提问来源于stack exchange,提问作者Bhanu Partap
相关产品推荐
相关产品推荐

