Uncaught TypeError: Cannot read properties of null (reading ‘…’) とは
JavaScript開発中に「Uncaught TypeError: Cannot read properties of null (reading ‘…’)」というエラーに遭遇することは非常に一般的です。このエラーは、null値の変数やプロパティに対して、存在しないプロパティやメソッドにアクセスしようとしたときに発生します。これは、DOM要素の取得失敗やAPIからの予期せぬnullレスポンスが主な原因です。
エラーの発生パターン
このエラーは主に以下のようなケースで発生します。
パターン1: DOM Element Not Found
// HTMLにid="myButton"を持つ要素が存在しない場合
const button = document.getElementById('myButton');
button.addEventListener('click', () => { // buttonがnullなのでエラー
console.log('Button clicked!');
});
document.getElementById()などが要素を見つけられなかった場合、nullを返します。そのnullに対してaddEventListenerのようなメソッドを呼び出すと、このTypeErrorが発生します。
const button = document.getElementById('myButton');
if (button) { // nullチェックを追加
button.addEventListener('click', () => {
console.log('Button clicked!');
});
} else {
console.error('Button not found!');
}
パターン2: API Response Returns Null Property
// APIレスポンスでuserオブジェクトがnullになる可能性を考慮していない
const response = { data: { user: null } }; // 例としてuserがnull
console.log(response.data.user.name); // userがnullなのでエラー
外部APIからのデータや、複雑なオブジェクト構造を扱う際に、一部のプロパティがnullである可能性を考慮せずにアクセスするとエラーになります。
const response = { data: { user: null } };
// オプショナルチェイニング (?.) を使用してnull安全にアクセス
console.log(response.data.user?.name); // userがnullならundefinedを返す
// または、明示的なnullチェック
if (response.data.user) {
console.log(response.data.user.name);
} else {
console.log('User data is null.');
}
パターン3: Variable Initialized to Null and Used Prematurely
let data = null;
// 何らかの処理の後にdataに値が代入されるはずが、されなかった
// ...
console.log(data.length); // dataがnullのままなのでエラー
変数をnullで初期化し、その後期待される値が代入されないままそのプロパティにアクセスするとエラーになります。特に非同期処理でよく見られます。
let data = null;
// 何らかの処理の後、dataに値が代入される
// data = [1, 2, 3]; // 例として代入
if (data !== null) { // nullチェック
console.log(data.length);
} else {
console.log('Data is null.');
}
根本原因の特定方法
エラーが発生した行番号を確認し、その行でアクセスしようとしている変数の値が何であるかをconsole.log()を使って確認しましょう。特に、オブジェクトの階層をたどる途中でどの部分がnullになっているのかを特定することが重要です。
const myObject = {
prop1: {
prop2: null
}
};
console.log(myObject); // { prop1: { prop2: null } }
console.log(myObject.prop1); // { prop2: null }
console.log(myObject.prop1.prop2); // null
// console.log(myObject.prop1.prop2.value); // ここでエラー
防止策とベストプラクティス
プロパティにアクセスする前に、値がnullでないことを常に確認する習慣をつけましょう。JavaScriptのオプショナルチェイニング(?.)や論理AND演算子(&&)は、簡潔にnullチェックを行うのに非常に有効です。
const user = null; // または { name: 'Alice' }
// オプショナルチェイニング
const userName = user?.name; // userがnullならundefinedになる
console.log(userName);
// 論理AND演算子
const anotherUser = { profile: { email: 'test@example.com' } };
const userEmail = anotherUser.profile && anotherUser.profile.email;
console.log(userEmail);
よくある質問(FAQ)
-
Q
nullとundefinedの違いは何ですか? -
A
nullは「値が存在しない」ことをプログラマが意図的に割り当てるプリミティブ値です。一方、undefinedは「変数が宣言されたが値が割り当てられていない」状態や、「存在しないプロパティにアクセスした」場合にJavaScriptエンジンによって設定される値です。
-
Qこのエラーは非同期処理でなぜよく発生するのですか?
-
A
非同期処理では、データがまだ取得できていない間に、そのデータにアクセスしようとすることがよくあります。例えば、APIコールが完了する前にレスポンスオブジェクトのプロパティにアクセスしようとすると、レスポンスが
nullのままでこのエラーが発生する可能性があります。
-
Qオプショナルチェイニング(
?.)はどのように役立ちますか? -
A
オプショナルチェイニングは、オブジェクトのプロパティチェーンを安全にアクセスするための構文です。チェーンの途中に
nullまたはundefinedのプロパティがあっても、エラーを発生させずにundefinedを返します。これにより、冗長なnullチェックを減らし、コードを簡潔に保つことができます。




コメント