ethers.js报错:Wallet.fromMnemonic不是函数,如何解决?
问题原因与解决方案
问题根源
这个错误的核心是ethers.js版本不兼容:在ethers.js v6及以上版本中,Wallet.fromMnemonic()方法已被移除,改用了更直观的Wallet.fromPhrase()方法;而你的代码写法是v5版本的API。
修正方案
方案1:适配ethers.js v6(推荐)
直接使用v6提供的新API,有两种写法:
- 更高效的方式:直接从
createRandom()结果获取钱包实例,同时可提取助记词const userWallet = ethers.Wallet.createRandom(); // 获取助记词短语 const mnemonicPhrase = userWallet.mnemonic.phrase; - 已有助记词短语时,用
fromPhrase()创建钱包const userWalletKeys = ethers.Wallet.createRandom().mnemonic; const userWallet = ethers.Wallet.fromPhrase(userWalletKeys.phrase);
方案2:回退到ethers.js v5
如果需要保留原有代码逻辑,可以安装v5版本的ethers.js:
npm install ethers@5
安装完成后,你的原代码就能正常运行。
注意事项
ethers.js v6对API做了大量精简和优化,建议优先使用最新版本的写法,避免后续版本迭代带来的兼容性问题。
内容的提问来源于stack exchange,提问作者Radu Bogdan
相关产品推荐
相关产品推荐

