Fri Apr 14 2023

[SOLVED] React-Redux Uncaught Error: A state mutation was detected between dispatches

How to solve the "Uncaught Error: A state mutation was detected between dispatches" thrown by redux

I came across the above React-redux error recently and it had me scratching my head for a fair amount of time as the path and the component the error was pointing me towards did not have anything obviously wrong. 

After a few hours of debugging, I discovered the issue lay in a method that was used across a fair number of components, which was actually what made it hard to find. 

This method was being called on every render and looked something like this 

1const sortImages = (images) => {
2 return images.sort((a, b) => a.date - b.date);
3};

The issue here is that we are mutating the method param that is being passed into this method. The solution to this is to clone the incoming array of images and sort that as shown below!

1const sortImages = (images) => {
2 const imagesArray = [...images];
3 return imagesArray.sort((a, b) => a.date - b.date);
4};

Now Eslint has a very useful rule here called no-param-reassign that would warn you against such direct mutations, and I highly recommend that you enable it.

Did you find this article helpful or would like to see me write on something else? Let me know!

Comments