如何将ethers.js从5.7.2降级至5.6.1?NFT市场开发报错求助
解决NFT Marketplace创建NFT时的TypeError: Cannot read properties of undefined (reading 'length')错误
问题重现
点击“Create an NFT”按钮时触发未处理运行时错误,错误栈如下:
TypeError: Cannot read properties of undefined (reading 'length'). Call Stack toUtf8Bytes node_modules\@ethersproject\strings\lib.esm\utf8.js (176:20) StringCoder.encode node_modules\@ethersproject\abi\lib.esm\coders\string.js (12:47) eval node_modules\@ethersproject\abi\lib.esm\coders\array.js (49:0) Array.forEach <anonymous> pack node_modules\@ethersproject\abi\lib.esm\coders\array.js (43:0) TupleCoder.encode node_modules\@ethersproject\abi\lib.esm\coders\tuple.js (51:19) AbiCoder.encode node_modules\@ethersproject\abi\lib.esm\abi-coder.js (86:0) Interface._encodeParams node_modules\@ethersproject\abi\lib.esm\interface.js (253:0) Interface.encodeFunctionData node_modules\@ethersproject\abi\lib.esm\interface.js (295:0) eval node_modules\@ethersproject\contracts\lib.esm\index.js (125:0) Generator.next <anonymous> fulfilled node_modules\@ethersproject\contracts\lib.esm\index.js (5:42)
已尝试的方案
- 修改.env文件中的Infura
projectId和projectSecret,同时调整create-nft.js中的createitem函数 - 尝试将ethers.js降级到5.6.1,但不清楚具体操作步骤
解决方案
1. 优先排查合约调用参数
错误本质是ethers编码ABI参数时,某个预期为字符串/数组的参数是undefined,导致读取length失败:
- 检查
createitem函数传入合约的参数(如NFT名称、描述、元数据URL等),确保所有必填字段都已赋值 - 确认前端表单输入是否正确传递到合约调用逻辑,避免空值提交
2. 降级ethers.js到5.6.1的具体步骤
如果确认是版本兼容问题,按以下操作执行:
- 打开项目根目录的终端
- 卸载当前ethers相关包:
npm uninstall ethers @ethersproject/abi @ethersproject/strings @ethersproject/contracts - 安装指定版本的包:
npm install ethers@5.6.1 @ethersproject/abi@5.6.1 @ethersproject/strings@5.6.1 @ethersproject/contracts@5.6.1 - 若使用yarn,对应命令:
yarn remove ethers @ethersproject/abi @ethersproject/strings @ethersproject/contracts yarn add ethers@5.6.1 @ethersproject/abi@5.6.1 @ethersproject/strings@5.6.1 @ethersproject/contracts@5.6.1 - 安装完成后重启开发服务器,重新测试创建NFT功能
3. 额外检查项
- 确认Hardhat版本与ethers 5.6.1兼容,建议Hardhat版本保持在2.9.x区间
- 检查.env文件中的Infura配置是否正确读取,避免变量名拼写错误
内容的提问来源于stack exchange,提问作者MochaOverChai
相关产品推荐
相关产品推荐

