Skip to content

useMutation has compatibility issue with <StrictMode> #9826

@RSATom

Description

@RSATom

Describe the bug

the problem is following code gives pending state for mutation even after onError definitely called.

function MutationTest() {
  const mutation = useMutation({
    mutationFn: async () => {
      console.log("mutationFn")
      throw new Error()
    },
    onError: () => { console.log("useMutation onError") }
  })

  console.log("mutation.status", mutation.status)

  const mutationIsActiveRef = useRef(false)
  useEffect(() => {
    if(mutation.isIdle && !mutationIsActiveRef.current) {
      mutationIsActiveRef.current = true;
      console.log("mutate")
      mutation.mutate(
        undefined,
        {
          onError: () => { console.log("mutate onError") },
          onSettled: () => { mutationIsActiveRef.current = false }
        },
      )
    }
  }, [mutation])

  return <span>Mutation status: { mutation.status }</span>
}

mutationIsActiveRef is required to be sure mutation started only once, since when <StrictMode> is enabled useEffect called at least twice: https://react.dev/blog/2022/03/29/react-v18#new-strict-mode-behaviors

Your minimal, reproducible example

https://github.com/RSATom/mutation-issue

Steps to reproduce

Just run demo and see pending state for mutation instead of error.

Expected behavior

mutation should have status = "error"

How often does this bug happen?

Every time

Platform

# lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 25.04
Release:	25.04
Codename:	plucky

Google Chrome: Version 142.0.7444.59 (Official Build) (64-bit)
Firefox: 144.0 (64-bit)

Tanstack Query adapter

react-query

TanStack Query version

5.90.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions