解决 Vue 报错 Cannot read properties of undefined 指南
分析 Vue 模板或组件在异步数据未返回前渲染报 Cannot read properties of undefined 的可选链与 v-if 保护方案。
问题现象
在 Vue 3 或 Vue 2 应用中打开页面时,页面无法正常展示,控制台报错:
[Vue warn]: Unhandled error during execution of render function
TypeError: Cannot read properties of undefined (reading 'avatar')
at Proxy._sfc_render (Profile.vue:15)
触发根因
- 页面模板中读取了深层嵌套属性(如
user.profile.avatar)。 user或profile是通过异步 API 接口请求获取的。在网络响应返回之前,响应式数据初始值为undefined或空对象{},模板初次渲染时尝试读取未定义对象的属性。
解决步骤与操作命令
步骤一:使用可选链操作符(Optional Chaining)
在 Vue 模板中直接使用 ?. 安全取值:
<template>
<div class="user-card">
<img :src="user?.profile?.avatar || '/default-avatar.png'" />
<h2>{{ user?.name }}</h2>
</div>
</template>
步骤二:使用 v-if 保护整个渲染块
在根元素上等待异步数据完全就绪后再进行子树渲染:
<template>
<div v-if="user && user.profile" class="user-card">
<img :src="user.profile.avatar" />
<h2>{{ user.name }}</h2>
</div>
<div v-else class="loading">
正在加载用户数据...
</div>
</template>
步骤三:在 Composition API 中初始化完整的数据模型骨架
const user = ref({
name: '',
profile: {
avatar: ''
}
});
验证确认
刷新应用页面并在慢速网络(Slow 3G)下进行测试: 在请求等待期间页面展示占位 Loading,数据返回后顺利更新,无任何控制台报错。


