editor icon indicating copy to clipboard operation
editor copied to clipboard

[BUG] Setting state in `onError` leads to React warning about setState called during render

Open lilactown opened this issue 2 months ago • 4 comments

  • [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
  • [x] I have read the documentation and cannot find an answer.

Describe the bug When passing a state setter to the onError prop of MDXEditor, React prints a warning similar to

hook.js:608 Cannot update a component (`DocumentPage`) while rendering a different component (`RealmWithPlugins`). To locate the bad setState() call inside `RealmWithPlugins`, follow the stack trace as described in https://react.dev/link/setstate-in-render

Reproduction https://stackblitz.com/edit/github-qekvbmto?file=package.json

To Reproduce Steps to reproduce the behavior:

  1. Navigate to the link above
  2. Open dev console

Expected behavior No errors or warnings are presented to the developer in the console

Desktop (please complete the following information):

  • OS: macOS
  • Browser: Chrome

Additional context My hunch is this is due to the way gurx propagates values on change- perhaps instead of calling onError directly in the signal setup in the core plugin, using an effect would stop this from happening.

lilactown avatar Oct 16 '25 21:10 lilactown

You can use a any kind of a delay mechanism in the setter to avoid that - that's what the internal implementation would do anyway.

petyosi avatar Oct 17 '25 03:10 petyosi

I ended up doing this to quiet the error:

onError(({ error }) => setTimeout(() => setError(error), 0))

However, this could be broken in concurrent mode, since this is still a side effect during render.

Best practice would be to schedule it to run after the MDXEditor update that triggers the error is committed, i.e. via a useEffect

lilactown avatar Oct 17 '25 16:10 lilactown

@lilactown I'm not certain on the canonical React way here, but would not throwing an Error + an ErrorBoundary around the component work too?

petyosi avatar Oct 20 '25 07:10 petyosi

Yes, that would also work! And do away with the onError callback, I presume

lilactown avatar Oct 20 '25 21:10 lilactown