MeWrite Docs

Cannot read property 'x' of undefined

undefinedのプロパティにアクセスしようとした場合に発生するエラー

概要

Cannot read property 'x' of undefinedは、JavaScriptで最も頻繁に発生するエラーの1つです。undefinedまたはnullの値に対してプロパティアクセスを試みた場合に発生します。

エラーメッセージ

TypeError: Cannot read property 'name' of undefined
    at Object.<anonymous> (app.js:10:15)

原因

  1. 変数が未定義: オブジェクトが存在しない状態でプロパティにアクセス
  2. APIレスポンスが空: 期待したデータが返ってこない
  3. 非同期処理のタイミング: データ取得前にアクセス

解決策

1. オプショナルチェイニング(ES2020)

1
2
3
4
5
// 従来の書き方
const name = user && user.profile && user.profile.name;

// オプショナルチェイニング
const name = user?.profile?.name;

2. デフォルト値を設定

1
2
3
4
const name = user?.profile?.name ?? 'Unknown';

// または
const { name = 'Unknown' } = user?.profile ?? {};

3. 事前にチェック

1
2
3
if (user && user.profile) {
    console.log(user.profile.name);
}

4. try-catchでエラーハンドリング

1
2
3
4
5
try {
    const name = user.profile.name;
} catch (error) {
    console.log('User profile not available');
}

JavaScript の他のエラー

最終更新: 2025-12-09