Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug ReactJS's setState

Tags:

reactjs

I'm currently working on a medium sized reactJS application and get the following error message after I click a button on a component:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

How can I debug this more easily? Why doesn't reactJS give me a specific component name where this rule was violated?

How would you do it?

like image 471
Tim Daubenschütz Avatar asked Dec 05 '22 21:12

Tim Daubenschütz


2 Answers

You can override console.warn to make it throw instead of log when the provided message matches a certain pattern. In your case, you'd do:

var warn = console.warn;
console.warn = function(warning) {
  if (/(setState)/.test(warning)) {
    throw new Error(warning);
  }
  warn.apply(console, arguments);
};

The stack trace of the error will then point to the line causing the warnings.

like image 184
Alexandre Kirszenberg Avatar answered Dec 31 '22 01:12

Alexandre Kirszenberg


Actually, the best way to solve this issue is by changing some react code locally.

This pull-request specifically points out how to modify src/renderers/shared/reconciler/ReactUpdateQueue.js to get the component that illegaly sets state.

As this pull-request was already merged into the repo, it shouldn't be to long before it will be integrated into an npm version of react, one could hope.

like image 30
Tim Daubenschütz Avatar answered Dec 31 '22 02:12

Tim Daubenschütz