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

Nuxt3中useFetch获取的API JSON对象无法正常访问的问题

问题原因与解决方案:Nuxt3 useFetch无法正确解析响应

核心问题

你错误地将useFetch的返回值当作原始JSON字符串处理了。Nuxt3的useFetch方法返回的不是API响应的原始文本,而是一个包含响应状态、解析后数据的响应对象,直接对它执行JSON.parse会抛出错误。

具体分析

  • 注释中能正常工作的代码,是直接使用了原始JSON字符串,JSON.parse可以正确将其转为对象;
  • 而useFetch的返回值结构如下(简化版):
    {
      data: Ref(/* API返回的已解析对象 */),
      pending: Ref(false),
      error: Ref(null),
      // 其他属性
    }
    
    API返回的JSON已经被Nuxt自动解析为JavaScript对象,存储在data.value中,不需要再手动调用JSON.parse。

修正后的代码(选项式API)

<template>
  <div>
        {{ test }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      test: null
    };
  },
  async created() {
    try {      
      // 解构获取useFetch返回的data和error
      const { data, error } = await useFetch('https://reqres.in/api/users/2')

      // 处理请求错误
      if (error.value) {
        throw error.value
      }

      // 直接访问已解析的对象,无需JSON.parse
      this.test = data.value.data.id
    } catch (err) {
      console.log(err);
    }
  }
};
</script>

<style scoped></style>

更推荐的组合式API写法(Nuxt3官方推荐)

<template>
  <div>
    {{ test }}
  </div>
</template>

<script setup>
// 直接在setup中使用useFetch
const { data, error } = await useFetch('https://reqres.in/api/users/2')

// 安全获取id值
const test = data.value ? data.value.data.id : null

// 捕获错误
if (error.value) {
  console.error('请求出错:', error.value)
}
</script>

总结

  1. useFetch会自动解析API返回的JSON响应,无需手动调用JSON.parse;
  2. 需通过返回对象的data.value获取实际的响应数据;
  3. 可以同时解构出error属性来处理请求失败的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:42:40