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

使用Axios调用CoinGecko API刷新页面时出现undefined问题求助

问题原因分析

你遇到的问题本质是异步请求未完成时,模板提前尝试访问了不存在的嵌套属性:

  1. 初始时你把coin.data设为数组[],但API返回的是对象,初始状态下market_data、current_price这些嵌套属性完全不存在;
  2. 页面刷新时,组件先渲染模板,此时异步请求还在处理中,读取coin.data.market_data.current_price.usd相当于读取undefined.current_price.usd,直接抛出错误;
  3. 热更新时,组件重新渲染前请求可能已经完成,数据已存在,所以不会报错。
解决方法

方法一:初始化匹配数据结构

给coin.data设置与API返回结构一致的空初始值,确保模板访问的每个层级都有默认值:

const coin = reactive({
  data: {
    name: '',
    market_data: {
      current_price: {
        usd: 0
      }
    }
  }
});

这样即使请求未完成,模板访问嵌套属性时也能拿到默认值,不会报错。

方法二:使用可选链操作符?.

在模板中用?.安全访问嵌套属性,当某个层级不存在时会返回undefined,但不会抛出错误,还可以配合??设置加载提示:

<div class="font-bold text-xl mb-2">{{coin.data.name ?? 'Loading...'}}</div>
<table class="table-fixed">
  <tbody>
    <tr>
      <th>Price</th>
      <td>{{coin.data.market_data?.current_price?.usd ?? 'Loading...'}}</td>
    </tr>
  </tbody>
</table>

方法三:添加加载状态控制渲染

定义加载状态,请求完成前不渲染需要嵌套数据的部分,避免提前访问不存在的属性:

<template>
  <div class="max-w-sm rounded overflow-hidden shadow-lg bg-white" v-if="!isLoading">
    <div class="px-6 py-4">
      <div class="font-bold text-xl mb-2">{{coin.data.name}} Price Statistics</div>
      <table class="table-fixed">
        <tbody>
          <tr>
            <th>Price</th>
            <td>{{coin.data.market_data.current_price.usd}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <div v-else class="max-w-sm rounded overflow-hidden shadow-lg bg-white px-6 py-4">
    Loading...
  </div>
</template>

<script setup>
import { api } from '../services/api'
import { reactive, ref } from 'vue'

const props = defineProps(['coinId'])
const isLoading = ref(true)

const coin = reactive({
  data: {}
});

async function fetchData() {
  try {
    const response = await api.get(`/coins/${props.coinId}`)
    coin.data = response.data
  } catch (e) {
    console.error(e)
  } finally {
    isLoading.value = false
  }
}

fetchData()
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:27:05