A non-serializable value was detected in the state : 리덕스 툴킷 에러

한호수 (The Lake)·2022년 12월 25일
0

react_devtools_backend.js:4012 A non-serializable value was detected in the state, in the path: func. Value: () => console.log("test")
Take a look at the reducer(s) handling this action type: toDosReducer/test.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)

문제

const testSlice = createSlice({
  name: "testReducer",
  initialState: {},
  reducers: {
    test: (state, action) => {
      return { func: () => console.log("test") }; // state에 함수를 넣어 Error
    },
  },
});

// or 
console.log(typeof test) // function
dispatch({ type: test, payload: { name:"name" } }); // dispatch의 action type에 함수를 넣어서 Error
  • Redux의 Store State 또는 Action에 직렬화 할 수 없는 값을 저장하게 되면 해당 경고가 발생합니다. (기능은 작동될 수 있음)
  • 직렬화할 수 없는 항목을 저장소에 삽입하는 것은 기술적으로 가능하지만 그렇게 하면 저장소의 콘텐츠를 유지하고 복원하는 기능이 손상될 뿐만 아니라 시간 여행 디버깅(Redux Devtools의 기능)을 방해할 수 있습니다.
  • 지속성 및 시간 여행 디버깅과 같은 것이 잠재적으로 의도한 대로 작동하지 않는 것에 대해 괜찮다면 직렬화할 수 없는 항목을 Redux 스토어에 넣는 것을 전적으로 제한하지 않습니다.

해결방법

  1. Store State에 함수 및 직렬화가 불가능한 값들을 저장하지 않고 컴포넌트 내부에서 작성해서 사용한다. (권장)
  2. 직렬화 가능한 값을 체크하는 미들웨어를 사용하지 않는다.
import {getDefaultMiddleware} from "@reduxjs/toolkit";

const store = configureStore({
  reducer: testSlice.reducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware({
   serializableCheck: false,
  })
});
  1. createAsyncThunk 함수를 사용하여 Store에 함수를 저장한다. (올바른 방법인지 확인 안됨)
export const printTest = createAsyncThunk("printTest", (state, action) => {
  return console.log("test");
});

// Home.jsx
import printTest from "./store.js";

dispatch(printTest()); // "test"

용어설명

  • non-serializable value란? Promises, Symbols, Maps/Sets, functions, class instances 로 직렬화 할 수 없는 값을 의미한다.
  • serializable(직렬화) 란? 어떤 프로그램 상에서 사용하고 있는 Object나 데이터 구조를 바이트 형태로 바꿔서 다른 환경 등에서도 사용할 수 있는 형태(ex. String)로 바꾸어 주는것

공식사이트 관련내용
https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state
https://redux.js.org/style-guide/#do-not-put-non-serializable-values-in-state-or-actions

profile
항상 근거를 찾는 사람이 되자

0개의 댓글