web3.js 4.x连接MetaMask报BigInt序列化错误求助
web3.js 4.x连接MetaMask时BigInt序列化错误解决方案
你遇到的错误源于web3.js 4.x内部大量使用BigInt类型,而Redux默认序列化机制无法处理该类型——当你尝试将整个web3实例通过dispatch存入Redux状态时,就会触发这个报错。旧版web3.js未大规模使用BigInt,因此不会出现此类问题。
方案1:避免将web3实例存入Redux(推荐)
Redux状态仅适合存储可序列化的简单数据(如字符串、数字、普通对象),web3实例包含大量不可序列化的方法和BigInt属性,不适合存入状态。可以将web3实例放在模块级变量或React Context中管理,仅将业务所需的可序列化数据(如账户地址、链ID)存入Redux。
修改后的代码示例:
// 模块级变量存储web3实例,全局可访问 let web3Instance; export const loadWeb3 = async (dispatch) => { console.log(Web3); web3Instance = new Web3(Web3.givenProvider || 'http://localhost:8545'); // 仅将需要的可序列化数据dispatch到Redux const chainId = await web3Instance.eth.getChainId(); const accounts = await web3Instance.eth.getAccounts(); dispatch(actions.web3Loaded({ chainId, account: accounts[0] })); return web3Instance; }; // 其他组件/函数需要使用web3时,调用此方法获取实例 export const getWeb3 = () => web3Instance;
方案2:配置Redux忽略BigInt序列化检查
如果确实需要在Redux中保留web3相关的BigInt数据,可以修改Redux的序列化检查规则,忽略特定的action或状态路径。
以Redux Toolkit为例,修改store配置:
import { configureStore } from '@reduxjs/toolkit'; import yourReducer from './reducers'; export const store = configureStore({ reducer: { app: yourReducer, }, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: { // 忽略web3Loaded这个action的序列化检查 ignoredActions: ['web3/web3Loaded'], // 或者忽略状态中存储web3实例的路径 ignoredPaths: ['app.web3Instance'], }, }), });
内容的提问来源于stack exchange,提问作者Zoubair ELhattab
相关产品推荐
相关产品推荐

