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

ReactNative集成Web3报Secure random number generation错误如何解决

问题根本原因

该报错的核心是Web3.js依赖的加密运算库需要调用window.crypto.getRandomValues接口生成安全随机数,React Native原生JS运行环境未提供该全局接口:浏览器调试时借用了调试工具的浏览器内核环境,存在对应接口所以运行正常,真机运行时使用纯RN JS运行环境,缺少接口就会触发报错。

解决方案

适配Expo项目

  1. 安装必要依赖
npm install react-native-get-random-values expo-crypto
# 或使用yarn
yarn add react-native-get-random-values expo-crypto
  1. 调整入口文件加载顺序,在项目入口文件(如index.js、App.js)的最顶部第一行引入polyfill,再引入Web3相关代码:
// 第一行引入polyfill
import 'react-native-get-random-values';
import * as Crypto from 'expo-crypto';

// 手动补全全局接口(如果引入polyfill后仍报错则添加这段)
if (typeof global.window === 'undefined') {
  global.window = {};
}
if (!window.crypto) {
  window.crypto = {};
}
window.crypto.getRandomValues = (typedArray) => {
  const randomValues = Crypto.getRandomBytes(typedArray.length);
  for (let i = 0; i < typedArray.length; i++) {
    typedArray[i] = randomValues[i];
  }
  return typedArray;
};

// 后续再引入Web3、钱包相关逻辑代码

适配纯React Native项目(非Expo)

  1. 安装依赖
npm install react-native-get-random-values
# iOS端执行pod安装
cd ios && pod install && cd ..
  1. 在项目入口文件最顶部第一行引入polyfill即可:
import 'react-native-get-random-values';
// 后续再引入Web3相关代码
验证排查注意事项
  • 必须保证polyfill的引入顺序早于Web3相关包的引入,顺序错误会导致polyfill不生效
  • 调整代码后清除缓存重新打包运行:执行npx react-native start --reset-cache重启打包服务,iOS端可删除DerivedData后重新编译
  • 如果仍存在适配问题,可改用ethers.js替代Web3.js,该库对React Native环境的适配更友好,无需额外配置大量polyfill即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:45:03