Warning: Can't perform a React state update on an unmounted component. [BUG@Zustand 2.2+]
See original GitHub issueHello, I’ve been using zustand to try out new React applications, however, I’m getting this warning from React when I change my state by using the API.setState:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. in Login (at app.tsx:39)
This is the code:
import React from 'react'
import create from 'zustand'
import shallow from 'zustand/shallow'
const [useAuthStore, authStoreApi] = create(() => ({
authenticated: false,
password: ''
}))
const setPassword = (password) => authStoreApi.setState({ password })
const authenticate = async () => {
await new Promise((resolve) => setTimeout(resolve, 1000))
authStoreApi.setState({ authenticated: true })
}
const Login = () => {
const [authenticated, password] = useAuthStore(
(store) => [store.authenticated, store.password],
shallow
)
return (
<div>
<span>authenticated: {authenticated ? 'yes' : 'no'}</span>
<input value={password} onChange={(e) => setPassword(e.target.value)} />
<button type="button" onClick={authenticate}>
authenticate
</button>
</div>
)
}
const Home = () => <div>Welcome!</div>
export const App = () => {
const authenticated = useAuthStore((store) => store.authenticated)
return (
<div>
{authenticated && <Home />}
{!authenticated && <Login />}
</div>
)
}
It works when I fetch singular props, e.g. const password = useAuthStore(store => store.password)
, or when I use array-selector with one entity AND use the shallow-comparator. But using multiple state picks with or without the shallow-comparator leaves me with this React-error.
Did anyone have any similar issue?
React version: 16.13.1 Zustand version: 2.2.3
EDIT: It seems to work using Zustand 2.1.4
Thanks
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:7 (3 by maintainers)
Top GitHub Comments
This is due to a synchronous setState call.
authStoreApi.setState
is called after anawait
. It’s annoying but shouldn’t cause any issues and it will go away in the future: https://twitter.com/dan_abramov/status/959557687158689792No warning with batched updates: https://codesandbox.io/s/goofy-oskar-sbtst?file=/src/App.js
this error is shown only if you are using React StrictMode. But why?