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

生成以太坊加密密钥时遇Uncaught TypeError错误,如何修复?

修复Uncaught TypeError: Cannot read properties of undefined (reading 'utils')错误

这个错误的核心原因是你导入的secp对象中不存在utils属性——ethereum-cryptography库的模块化设计里,randomPrivateKey这类工具方法被拆分到了单独的子模块,而非挂载在默认导出的secp对象上。

修复步骤:

  • 新增randomPrivateKey的单独导入语句,从ethereum-cryptography/secp256k1/utils模块导入该函数
  • 直接调用导入的randomPrivateKey(),替换原来的secp.utils.randomPrivateKey()
  • 额外修复组件内的显示问题:原代码中直接渲染privateKey、publicKey会显示Uint8Array对象,需要用toHex转换为十六进制字符串才能正常显示

修复后的完整代码:

import secp from "ethereum-cryptography/secp256k1";
import { keccak256 } from "ethereum-cryptography/keccak";
import { toHex } from "ethereum-cryptography/utils";
import { randomPrivateKey } from "ethereum-cryptography/secp256k1/utils";

const privateKey = randomPrivateKey();
console.log('Private key:', toHex(privateKey));

const publicKey = secp.getPublicKey(privateKey);
console.log('Public key:', toHex(publicKey));

const address = keccak256(publicKey.slice(1)).slice(-20);
console.log('Ethereum address:', toHex(address));

function GenerateKey() {
    return (
        <div>
            <p>Private key: {toHex(privateKey)}</p>
            <p>Public key: {toHex(publicKey)}</p>
            <p>Address: {toHex(address)}</p>
        </div>
    )
}

export default GenerateKey;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 01:15:31