TypeError: Cannot read properties of undefined 해결 방법
TypeError: Cannot read properties of undefined (reading 'x')
증상
코드를 실행하면 콘솔에 다음과 같은 오류가 출력되고 그 지점에서 멈춥니다.
Uncaught TypeError: Cannot read properties of undefined (reading 'name')
reading '...' 안의 이름이 접근하려던 속성입니다. 즉 그 속성을 가진 객체가 undefined(또는 null)였다는 뜻입니다.
원인
undefined인 값의 속성에 접근했을 때 발생합니다. 대표적인 경우:
- 아직 도착하지 않은 비동기 데이터(API 응답 전)를 렌더링
- 배열에서
find()가 못 찾아undefined를 반환했는데 곧바로 속성 접근 - 객체에 없는 키를 거쳐 더 깊이 들어감
const user = undefined;
console.log(user.name); // ✕ Cannot read properties of undefined (reading 'name')
해결
1) 옵셔널 체이닝(?.)
값이 undefined/null이면 접근을 멈추고 undefined를 반환합니다.
const user = undefined;
console.log(user?.name); // undefined (오류 없음)
2) 기본값(??, 구조 분해 기본값)
const { name = '익명' } = user ?? {};
console.log(name); // '익명'
3) 데이터 로딩 가드(React 등)
if (!data) return null; // 또는 로딩 UI
return <span>{data.name}</span>;
핵심은 "속성에 접근하기 전에 그 객체가 정말 존재하는지" 확인하는 것입니다.
?.와??를 함께 쓰면 대부분 안전하게 해결됩니다.