TypeError:transactionContract.getAllTransactions非函数问题排查与解决
问题解决方案
核心错误原因
createEthereumContract 是异步函数,调用时未添加 await,导致返回的是Promise对象而非实际的ethers合约实例,因此无法找到 getAllTransactions 方法。
修复步骤
1. 补全异步调用的await关键字
在调用 createEthereumContract 的两处代码中添加 await,确保获取到真实的合约实例:
// 在getAllTransactions函数中 const transactionContract = await createEthereumContract(); // 在sendTransaction函数中 const transactionContract = await createEthereumContract();
2. 验证合约ABI与地址
- 确认
contractABI中包含getAllTransactions函数的完整定义,函数名、参数列表必须与部署的智能合约完全一致(大小写敏感)。 - 检查
contractAddress是否为目标合约的正确部署地址,避免复制时出现拼写错误。
3. 修复交易方法拼写错误
sendTransaction 中的 eth_ction 是拼写错误,需修正为 eth_sendTransaction:
await ethereum.request({ method: "eth_sendTransaction", // 修正此处拼写 params: [{ from: currentAccount, to: addressTo, gas: "0x5208", value: parsedAmount._hex, }], });
4. 补充未定义的connectWallet函数
Provider的value中声明了 connectWallet 但未实现,需补充连接钱包的逻辑:
const connectWallet = async () => { try { if(!ethereum) return alert("Please install metamask"); const accounts = await ethereum.request({ method: 'eth_requestAccounts' }); setCurrentAccount(accounts[0]); await getAllTransactions(); } catch(error) { console.log(error); } }
修复后关键代码示例
const getAllTransactions = async () =>{ try { if(!ethereum) return alert("Please install metamask") const transactionContract = await createEthereumContract(); const availableTransactions = await transactionContract.getAllTransactions(); const structuredTransactions = availableTransactions.map((transaction)=>({ addressTo: transaction.receiver, addressFrom: transaction.sender, timestamp: new Date(transaction.timestamp.toNumber() * 1000).toLocaleString(), message: transaction.message, keyword: transaction.keyword, amount: parseInt(transaction.amount._hex) / (10 ** 18) })) console.log(structuredTransactions) setTransactions(structuredTransactions) } catch(error){ console.log(error); } }
内容的提问来源于stack exchange,提问作者user16369468
相关产品推荐
相关产品推荐

