Skip to content

Bug: unstable_useMutableSource throws error when mutated before subscribe #19948

Closed

Description

@SreeniIO

React version: 0.0.0-experimental-94c0244ba

Steps To Reproduce

Mutating the external source during the initial render before subscribe throws error.

https://codesandbox.io/s/usemutablesource-7nbs6?file=/src/App.js

image

  1. Navigate to the above code sandbox
  2. Click on the Mutate button. Final Value is rendered without any error. (Success Mode)
  3. Toggle to Error Mode and click on the Mutate button again.
  4. Error thrown (and the UI is rendered with the Final Value when run from vscode)

Note: In our actual codebase (private), we are seeing this error at different instances e.g. component getting updated due to setState call in useLayoutEffect etc.

The current behavior

Seeing errors in development build.

image

The expected behavior

These errors thrown by useMutableSource should not showup on the UI and not passed to the error boundary as the component is eventually re-rendered with the latest state without any error.

Activity

  1. self-assigned this
    on Oct 2, 2020
  2. SreeniIO commented on Oct 7, 2020

    @SreeniIO
    Author

    I'm using this workaround for now

      try {
        value = useMutableSource(mutableSource, getSnapshot, defaultSubscribe);
      } catch (error) {
        throw new Promise((resolve) => resolve());
      }

    https://codesandbox.io/s/usemutablesource-forked-0suof?file=/src/App.js:1126-1269

  3. bvaughn commented on Jan 26, 2021

    @bvaughn
    Contributor

    Proposed solution (really just a better warning and error message) in #20665

  4. bvaughn commented on Jan 29, 2021

    @bvaughn
    Contributor

    @SreeniIO Thanks for the repro case and discussion. I've landed a solution in #20665 and I'd suggest reconsidering the workaround you mentioned. My reasoning is this (copied from the PR description):

    Mutating a mutable source (or any external variable) during render is not expected to be supported. However this error message misattributes the mutation as a React bug.

    Should this use case be supported?

    This seems very similar lazily initializing a ref so it might be tempting to think it's okay. Mutable sources are external though, so modifying them during render is a side effect which makes it unsafe and unsupported. So while we could "support" this case in a very limited way, we shouldn't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions