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

Vue.js报错Cannot read properties of undefined (reading 'text')求助

Vue异步加载questions数组时"Cannot read properties of undefined"错误解决办法

问题根源

API请求是异步操作,页面初始渲染时questions数组还未被填充,此时questions[currentQuestionIndex]为undefined,直接访问它的.text或.answers属性就会抛出错误。虽然后续数据加载完成后页面能正常显示,但初始渲染阶段的错误会被触发。

解决办法

方案1:使用可选链操作符(?.)

在模板中访问属性时添加?.,当目标值为undefined时会短路,避免继续访问后续属性:

<h2>Questions</h2>
<div class="quiz" :key="currentQuestionIndex">
  <h2>{{ questions[currentQuestionIndex]?.text }}</h2>
  <div class="answers-container">
    <div
      class="answer answer--option"
      v-for="(answer, index) in questions[currentQuestionIndex]?.answers || []"
      @click="selectAnswer(index)"
      :class="{
        'is-selected': chosenAnswers[currentQuestionIndex] == index,
      }"
      :key="index"
    >
      {{ answer.text }}
    </div>
  </div>
</div>

其中questions[currentQuestionIndex]?.answers || []确保当answers不存在时,v-for遍历空数组,避免迭代报错。

方案2:添加v-if判断,确保数据存在再渲染

给问题容器添加v-if,仅当questions[currentQuestionIndex]存在时才渲染对应区域:

<h2>Questions</h2>
<div class="quiz" :key="currentQuestionIndex" v-if="questions[currentQuestionIndex]">
  <h2>{{ questions[currentQuestionIndex].text }}</h2>
  <div class="answers-container">
    <div
      class="answer answer--option"
      v-for="(answer, index) in questions[currentQuestionIndex].answers"
      @click="selectAnswer(index)"
      :class="{
        'is-selected': chosenAnswers[currentQuestionIndex] == index,
      }"
      :key="index"
    >
      {{ answer.text }}
    </div>
  </div>
</div>

这种方式会在数据加载完成前隐藏问题区域,彻底避免初始渲染错误。

方案3:初始化默认结构(可选)

在组件的data中给questions设置符合结构的初始值,保证初始渲染时不会出现undefined:

data() {
  return {
    questions: [{ text: '', answers: [] }],
    currentQuestionIndex: 0,
    // 其他数据...
  }
}

该方案可配合加载状态提示使用,优化用户体验。

补充说明

你在generateQuestions内部打印日志正常,是因为该方法是在API响应返回后执行的,此时数据已经存在;而页面渲染在组件初始化阶段就已开始,早于API数据返回,因此会触发初始错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:40:07