← Debugging Guides

阅读中文版本

JavaScript — Cannot read properties of undefined (reading X)

Locate the undefined receiver by reading the stack, adding guards and tracing where the value should have been assigned.

beginnerdebuggingjavascript

Symptoms

  • TypeError: Cannot read properties of undefined (reading 'name')
  • The error appears only on specific data or after a refactor
  • It happens after an async fetch resolves
  • Destructuring a missing field throws

Possible causes

  • A value expected to be an object is undefined at runtime
  • An asynchronous result is used before it is available
  • A lookup or find returned undefined and was dereferenced
  • A typo or renamed field leaves the property undefined

Diagnosis steps

Read the stack to find the exact line

node --stack-trace-limit=50 app.js

Interpretation

The top application frame names the file and line, narrowing the search to one expression.

Log the receiver before the access

console.log({ value, keys: value && Object.keys(value) })

Interpretation

Seeing the receiver as undefined versus missing a key distinguishes a wrong object from a wrong property.

Trace where the value is assigned

grep -n "value =" src

Interpretation

Following the assignments reveals whether the value was never set or set later than used.

Root cause

The object being accessed is undefined at that point, so property access throws. The value was either never assigned, assigned after use, or replaced by undefined through a lookup.

Fix

Guard the access with optional chaining or an explicit check, ensure asynchronous results are awaited before use, and fix the assignment so the object exists when accessed.

Verify the fix

Rerun the failing path and confirm the error is gone, and confirm the property now holds the expected value rather than merely not throwing.

Symptom walkthrough

The code throws TypeError: Cannot read properties of undefined (reading something), which means the object to the left of the dot is undefined, not that the property is wrong. It frequently appears after a refactor, on specific data, or when a value from an asynchronous call is used before it resolves. Reading the stack names the exact expression, so the next step is to find where that object should have come from.

Fix in practice

Guard the access with optional chaining where absence is acceptable, or with an explicit check and a clear error where it is not. Await asynchronous results before use, and repair the assignment path so the object exists at the point of access. A guard alone does not fix a value that should never have been undefined.

Verification

Rerun the failing path and confirm the error is gone, then confirm the property holds the intended value. Not throwing is necessary but not sufficient; the value must also be correct.

Diagnostic commands

Check the behavior with commands like these:

node --stack-trace-limit=50 app.js
console.log({ value, keys: value && Object.keys(value) })
grep -n "value =" src