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

使用Alchemy API查询以太坊交易时遇函数未定义错误求助

问题:提交表单时提示Uncaught ReferenceError: fun is not defined,Alchemy API交易查询失败

问题原因

  1. 脚本类型配置错误:HTML中引入alchemy-test.mjs时,script标签的type设置为alchemy-sdk,浏览器无法识别该类型,导致模块未正确加载,函数无法暴露。
  2. ES模块作用域限制:即使模块正确加载,ES模块内部定义的fun函数默认仅在模块作用域内有效,不会挂载到全局window对象,因此表单的onsubmit="fun()"无法找到该函数。
  3. 逻辑执行时机错误:当前代码在模块加载完成后立即执行alchemy.core.getAssetTransfers,但此时用户还未输入地址,且addr变量仅在fun函数内部定义,外部无法访问,会引发额外错误。

修复步骤

  1. 修正script标签的type为module,让浏览器正确识别ES模块。
  2. 移除表单的onsubmit属性,改为在模块中通过事件监听处理提交逻辑(避免全局作用域污染)。
  3. 将API查询逻辑封装到提交回调中,确保获取用户输入后再执行查询,并阻止表单默认刷新行为。

修复后的完整代码

HTML代码

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project</title>
</head>
<body>
    <h3>Ethereum Blockchain Query</h3>
    <form name="dati" style="border:0px" action="" method="post"> <br>
        Wallet address: <input type="text" id="address" name="address" placeholder="Enter address"><br><br>
        <input type="submit" value="Submit"><br>
        <input name="Reset Data" type="reset" value="Reset Data">   
    </form>
    <br><br>
    <script type="module" src="alchemy-test.mjs"></script>
</body>
</html>

alchemy-test.mjs代码

// Setup: npm install alchemy-sdk
import { Alchemy, Network } from "alchemy-sdk";

const settings = {
    apiKey: "######################",
    network: Network.ETH_MAINNET,
};

const alchemy = new Alchemy(settings);

// 获取表单元素并监听提交事件
const form = document.querySelector('form[name="dati"]');
form.addEventListener('submit', async (e) => {
    // 阻止表单默认提交刷新行为
    e.preventDefault();
    // 获取用户输入的地址
    const addr = document.getElementById("address").value;
    if (!addr) {
        console.log("请输入钱包地址");
        return;
    }
    try {
        // 调用Alchemy API查询交易
        const res = await alchemy.core.getAssetTransfers({
            fromBlock: "0x0",
            toBlock: "latest",
            fromAddress: addr,
            excludeZeroValue: true,
            category: ["erc20", "external"],
            maxCount: "0x3e8"
        });
        console.log(res);
    } catch (err) {
        console.error("查询失败:", err);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:05:31