[Error] Uncaught (in promise) Error: Invariant failed: A state mutation was detected between dispatches
Post

[Error] Uncaught (in promise) Error: Invariant failed: A state mutation was detected between dispatches

Uncaught (in promise) Error: Invariant failed: A state mutation was detected between dispatches

Error Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { useSelector, useDispatch } from 'react-redux';
import { resetTemplate, selectTemplate } from './AssignSlice';

/**
 * template 
 * {name:'template name', items: [{text: 'apple'}]}
 **/
const template = useSelector(selectTemplate);

useEffect(() => {
    template.items.forEach(item => {
        item.text = 'orange';
    });
}, []);

Cause

Redux expects that all state updates are done immutably.

redux에 저장된 state값을 Mutable하게 변경하였기 때문에 발생한 오류이다. (같은 메모리 주소에 값만 직접 변경)

Solution

redux에 저장된 state값은 Immutable해야 한다. 즉, state값을 변경할때는 메모리 주소가 다른 새로운 값을 복사하여 저장 또는 사용하여야 한다.

1
2
3
4
5
6
7
8
9
10
11
import loadash from 'lodash';

const template = useSelector(selectTemplate);
const templateCopy = loadash.cloneDeep(template.items);  // 복사

useEffect(() => {
    templateCopy.forEach(item => {
        item.text = 'orange';
    });
}, []);