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

汇率转换应用TypeError报错:无法读取undefined属性的解决方案

货币转换函数Promise拒绝错误解决方案

问题重现

执行控制台命令 convert(100, 'CAD', 'USD') 时,控制台抛出错误:

Paused on promise rejection TypeError: Cannot read properties of undefined

报错定位到代码第64行:

const rate = ratesByBase[from].rates[to];

核心原因

  1. API参数错误:原代码请求接口时使用了错误参数名base,apilayer的currency_data/live接口需用source指定基准货币。
  2. 返回数据结构不匹配:接口汇率数据存于quotes字段(格式如CADUSD: 0.73),而非原代码预期的rates字段,导致ratesByBase[from].rates为undefined,访问[to]触发类型错误。
  3. 缺少错误处理:未处理HTTP请求失败或API返回错误的情况,导致Promise直接拒绝未被捕获。

修复方案

1. 修正API请求参数与数据解析

修改fetchRates函数,修正参数名并转换返回数据为预期结构:

async function fetchRates(base = "USD") {
    // 修正接口参数为source
    const res = await fetch(`${endpoint}?source=${base}`, requestOptions);
    // 检查HTTP请求状态
    if (!res.ok) {
        throw new Error(`请求失败:${res.status}`);
    }
    const data = await res.json();
    // 检查API返回的成功状态
    if (!data.success) {
        throw new Error(`API错误:${data.error.info}`);
    }
    // 将quotes转换为{ 目标货币: 汇率 }的格式
    const rates = { [base]: 1 }; // 基准货币对自身汇率为1
    for (const [key, value] of Object.entries(data.quotes)) {
        const targetCurrency = key.slice(base.length);
        rates[targetCurrency] = value;
    }
    // 返回符合原代码预期的结构
    return { rates };
}

2. 修复模板字符串语法错误

原convert函数中的日志输出用单引号无法解析模板变量,改为反引号:

console.log(`${amount} ${from} 等于 ${convertedAmount} ${to}`);

3. 调用时添加错误捕获

由于convert是异步函数,调用时需通过try/catch捕获错误:

async function testConvert() {
    try {
        const result = await convert(100, 'CAD', 'USD');
        console.log("转换结果:", result);
    } catch (err) {
        console.error("转换失败:", err.message);
    }
}

testConvert();

验证效果

修改后执行testConvert(),控制台将正常输出转换结果,不再抛出Promise拒绝错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:20:41