Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cryptic React error "unstable_flushDiscreteUpdates: Cannot flush updates when React is already rendering."

I have been able to find limited information on this error and was hoping someone could take a deep dive into explaining exactly what causes this. I haven't changed any of the code that appears to be showing up in the call stack recently, so I was wondering if this is from a newer update?

like image 456
Mark Avatar asked Sep 26 '19 18:09

Mark


3 Answers

In my case, The error/warning was casued by the react-block-ui package. Currently there is an opened issue at github of that package. The issue hasn't been solved so far.

It's a react issue. You can check if any third-party-packages are causing this. You can check this to see exactly where the error is coming from. I found these comments from there -

// We're already rendering, so we can't synchronously flush pending work.
// This is probably a nested event dispatch triggered by a lifecycle/effect,
// like `el.focus()`. Exit.

I hope this helps.

like image 165
Mark Avatar answered Nov 17 '22 21:11

Mark


I spent quite some time debugging a similar issue on my project. In the end, we were calling focus inside a setState function, but this can be quite hidden by callbacks. In our case this was looking at this:

class ChildComponent extends React.Component {
  func() {
    this.setState(state => {
      // ... Doing something
      this.props.onStateChange();
      // ... Returning some state
    });
  }
}

And then elsewhere:

  onStateChange = () => {
    this.element.focus();
  };

  render() {
    return <ChildComponent onStateChange={this.onStateChange} />;
  }

I solved the problem by calling the callback in componentDidUpdate:

class ChildComponent extends React.Component {
  func() {
    this.setState(state => {
      // ... Doing something
      // ... Returning some state
    });
  }

  componentDidUpdate(prevProps, prevState) {
    if (compare(prevState, this.state)) {
      this.props.onStateChange();
    }
  }
}

Another possible solution: A colleague of mine also suggested to use requestAnimationFrame inside setState so that the call would be happening out of the render cycle.

Hope this will help some people coming here!

like image 1
JulienW Avatar answered Nov 17 '22 22:11

JulienW


My problem was putting the debugger inside the code. As soon as I removed it, the error went away. So just in case

enter image description here

like image 1
ZedBee Avatar answered Nov 17 '22 22:11

ZedBee