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

Vue3数据获取失败报错:Cannot read properties of null (reading 'data')

解决Vue3中"Cannot read properties of null (reading 'data')"报错

报错信息

Cannot read properties of null (reading 'data')
TypeError: Cannot read properties of null (reading 'data')
    at Proxy.render (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/templateLoader.js??ruleSet[1].rules[3]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/views/HomeView.vue?vue&type=template&id=9ea40744:32:439)
    at renderComponentRoot (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:952:16)
    at ReactiveEffect.componentUpdateFn [as fn] (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:5814:46)
    at ReactiveEffect.run (webpack-internal:///./node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js:217:19)
    at instance.update (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:5927:51)
    at setupRenderEffect (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:5935:5)
    at mountComponent (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:5725:5)
    at processComponent (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:5678:9)
    at patch (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:5166:11)
    at ReactiveEffect.componentUpdateFn [as fn] (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:5886:9)

相关代码

脚本部分

<script setup>
import logo from "@/assets/logoo.svg";
import { ref, watchEffect } from 'vue'

const home = ref(null)

const API_URL = 'https://url.monapi?locale='
const locales = ['en', 'fr']

const currentLocale = ref(locales[0])
const datas = ref(null)

watchEffect(async () => {
  const url = `${API_URL}${currentLocale.value}`
  datas.value = await (await fetch(url)).json()

  console.log(datas.value.data.attributes.text)
})
</script>

模板部分

<template>
  <main class="homepage">
    <div>
      <template v-for="locale in locales" :key="locale.id">
        <input type="radio"
          :id="locale"
          :value="locale"
          name="locale"
          v-model="currentLocale">
        <label :for="locale">{{ locale }}</label>
      </template>

      <p>vuejs/vue@{{ currentLocale }}</p>

      <!-- eslint-disable-next-line no-console -->
      <p>{{ datas.data?.attributes.text }}</p>
      <ul>
        <li v-for="{ id } in datas" :key="id">
          {{ id }}
        </li>
      </ul>
    </div>
  </main>
</template>

问题分析与修复方案

1. 补全可选链操作符

datas初始值为null,模板中datas.data?.attributes.text仅对data之后的属性做了空值保护,但datas本身为null时,访问datas.data会直接报错。需将可选链前置到datas:

<p>{{ datas?.data?.attributes.text }}</p>

2. 添加异步请求错误处理

fetch请求可能因API故障、网络问题返回失败状态,此时json()可能返回无效数据或报错。需添加try/catch捕获异常,并校验响应状态:

<script setup>
// ... 其他代码
watchEffect(async () => {
  try {
    const url = `${API_URL}${currentLocale.value}`
    const response = await fetch(url)
    if (!response.ok) throw new Error(`请求失败: ${response.status}`)
    datas.value = await response.json()
    console.log(datas.value?.data?.attributes?.text) // 给console输出也加可选链避免报错
  } catch (err) {
    console.error('数据获取失败:', err)
    datas.value = null // 重置状态或设置默认空对象
  }
})
</script>

3. 修正v-for遍历与key绑定

  • locales是字符串数组,每个元素无id属性,v-for的key应直接使用locale:
    <template v-for="locale in locales" :key="locale">
    
  • 模板中遍历datas错误:datas是API返回的对象(包含data字段),不是数组。若需遍历列表数据,需明确指向数组字段(比如datas?.data?.items,需根据你的实际API返回结构调整):
    <ul v-if="datas?.data?.items">
      <li v-for="item in datas.data.items" :key="item.id">
        {{ item.id }}
      </li>
    </ul>
    

4. 优化初始状态

可将datas的初始值设为空对象,减少空值判断的复杂度:

const datas = ref({})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:24:56