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

React.js中eth-crypto调用报错:Cannot read properties of undefined (reading 'call')

解决React + eth-crypto在Webpack 5下的加密报错问题

问题分析

报错Cannot read properties of undefined (reading 'call')源于Webpack 5不再自动polyfill Node.js核心模块(如crypto、stream),且之前的react-app-rewired配置未完整覆盖所需的依赖补全,导致eth-crypto底层的哈希函数初始化失败。

解决方案

1. 安装必要的Polyfill包

执行命令安装浏览器兼容的Node核心模块替代包:

npm install crypto-browserify stream-browserify buffer assert process --save-dev

2. 完善config-overrides.js配置

确保配置文件完整覆盖Webpack的fallback和全局变量注入:

const { override, addWebpackPlugin, addWebpackResolve } = require('customize-cra');
const webpack = require('webpack');

module.exports = override(
  // 配置Node核心模块的浏览器替代包
  addWebpackResolve({
    fallback: {
      crypto: require.resolve('crypto-browserify'),
      stream: require.resolve('stream-browserify'),
      buffer: require.resolve('buffer'),
      assert: require.resolve('assert'),
      process: require.resolve('process/browser'),
    },
  }),
  // 注入全局变量,避免依赖库找不到Buffer/process
  addWebpackPlugin(
    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
      process: 'process/browser',
    })
  )
);

3. 确认package.json的Scripts配置

确保启动/构建命令使用react-app-rewired:

"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-scripts eject"
}

4. 验证加密调用的正确性

确保传入的公钥格式符合eth-crypto要求(需为0x开头的字符串),示例代码:

import EthCrypto from 'eth-crypto';

// 生成测试密钥对(实际场景中使用合法公钥)
const testIdentity = EthCrypto.createIdentity();
const validPublicKey = testIdentity.publicKey;

// 正确调用加密方法
const encryptPublicKey = async () => {
  try {
    const encryptedData = await EthCrypto.encryptWithPublicKey(validPublicKey, validPublicKey);
    console.log('加密结果:', encryptedData);
  } catch (err) {
    console.error('加密失败:', err);
  }
};

关键说明

  • Webpack 5移除了默认的Node核心模块polyfill,必须手动指定浏览器兼容的替代包;
  • ProvidePlugin用于全局注入Buffer和process,避免依赖库在浏览器环境中找不到这些变量;
  • 公钥格式错误也可能导致底层加密逻辑异常,需确保传入的公钥是eth-crypto认可的有效格式。

内容的提问来源于stack exchange,提问作者Josif Hamed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:25:50