Skip to content

Latest commit

 

History

History
28 lines (22 loc) · 846 Bytes

File metadata and controls

28 lines (22 loc) · 846 Bytes

Error "setState on unmounted component" occurs occasionally

Scenario:

async function handleSubmit() {
    setPending(true)
    await post('/someapi') // component might unmount while we're waiting
    setPending(false)
}

This is a workaround (see sandbox above):

useEffect(() => {
    function handleChange() {
        setState(store.getState())
    }
    store.subscribe(handleChange)
    return () => store.unsubscribe(handleChange)
}, [])
  • This handles out-of-order responses with a ref (or local variable if dependency array is empty array)
  • It's discussed to remove the warning in this GitHub issue.