Skip to content

TypeError:读取 undefined 的属性

错误信息

                Cannot read properties of undefined (reading 'x')
              

快速摘要

你对一个值为 `undefined` 的变量取属性,比如 `obj.foo.bar` 中 `obj.foo` 是 `undefined`,再取 `.bar` 就报错。

为什么发生

  • 链式属性访问中某一层是 undefined,下一层访问就失败

  • 从 API 返回的数据结构变了,某个字段不存在

  • 数组本应有元素但实际为空,访问 arr[0].xarr[0]undefined

最小示例

✗ 错误代码
const user = {};
console.log(user.profile.name);
✓ 修复代码
const user = {};
console.log(user?.profile?.name);

user.profileundefined,再取 .name 就抛错。用可选链 user?.profile?.name 安全访问。

如何诊断

  • 阅读错误信息中括号里的属性名,定位是哪一层访问失败

  • 在出错前打印中间变量的值,找出哪一层是 undefined

  • 对照 API 文档或数据源,确认数据结构是否符合预期

如何修复

  • 使用可选链:obj?.foo?.bar,遇到 undefined 时安全返回 undefined

  • 访问前逐层判空:if (obj && obj.foo && obj.foo.bar)

  • 给数据加默认值:const bar = obj?.foo?.bar ?? defaultValue

如何预防

  • 对深层属性访问统一使用可选链 ?.

  • 在数据入口处做 schema 校验,尽早暴露结构问题

相关资源

相关术语

相关课程

相关练习

← 返回语言