-
Notifications
You must be signed in to change notification settings - Fork 47.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug: setState behaves sync when inside a promise callback and async when not. #20991
Comments
I recognize https://reactjs.org/docs/react-component.html#setstate This states that it does not always immediately update the component but when does it decide to do that and why? I'm worried this can lead to accidental bugs if this is non deterministic. Is there a way to force this to always be async for development purposes so people don't accidentally rely on this being sync? |
no but I'm running this on latest chrome. |
I found a tweet from 2018 that suggests the right answer: https://twitter.com/dan_abramov/status/959507572951797761 |
I'm not sure if it is still the case to be honest. I've since moved on to hooks which are a lot less weird to me =) In any case, I strongly suggest not to depend on it being synchronous. Because |
This is entirely standard and intentional behavior. Currently, React only batches state updates that happen within its own event handlers. Logic in a promise callback is outside that event handler tick and thus outside the batching wrapper, so it's processed synchronously You should also probably read Dan's extensive explanation at #11527 (comment) Note that this is true regardless of whether you're using hooks or classes. Also, in Concurrent Mode, state updates are always batched all the time. |
Closing since this is expected behavior. #20991 (comment) and are great answers #20991 (comment). |
These explanations are great, and thankyou for the links!! Would it be possible to get this officially documented? |
FWIW, the React team is currently working on a complete rewrite of the docs: Not sure what specifically will be in there, but I'm hopeful that some of the behavior like this will be covered. |
React version:
React 16.12.0
React-Dom 16.12.0
Steps To Reproduce
Link to code example:
https://codesandbox.io/s/badjokes-forked-3o08z?file=/src/index.js SetState
The current behavior
setState is sync inside a promise callback
The expected behavior
setState should always by async inside a promise callback
The text was updated successfully, but these errors were encountered: