개발자가 된 감자

Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]' 본문

Error 해결

Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]'

감자씨 2025. 2. 6. 02:02
728x90

React 프로젝트 진행 중

TS + Recoil 을 이용한 sessionStorage에서 받아온 데이터를 수정하면서 해당 오류가 발생했다.

 

Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]'

위 내용처럼 read only인, 즉 읽기 전용인 데이터를 수정하려고 하면서 발생한 것으로 보인다.

 

아래 코드처럼 받아온 배열 데이터를 reverse() 시키면서 오류가 났다.

const result = e.keyPath?.reverse().map((path) => {
  return { title: path };
});

 

해당 데이터를 스프레드 연산자를 통한 깊은 복사 처리 후, 다시 reverse() 했더니 문제없이 진행됐다.

let deepCopy = [{...e.keyPath}]; // 깊은 복사
const result = deepCopy?.reverse().map((path) => {
  return { title: path };
});

 

728x90
Comments