简体   繁体   中英

How to update local storage value before unmounting React modal login component

I want my home page to use the authorization token in local storage to fetch a signed-in user after a page refresh. Conditionally rendering the login modal and logout components unmounts the modal before the local storage is updated and causes the warning below. I tried setting _mount to true in componentDidMount and false in componentWillUnmount in the login modal component, but I still got the warning and unwanted effect.

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 Formik (created by WithFormik(ModalContainer))
    in WithFormik(ModalContainer) (created by ConnectFunction)
    in ConnectFunction (at Header.js:64)
    in a (created by MenuItem)
    in MenuItem (at Header.js:59)

Please see this sandbox to reproduce a similar warning.

I did download your sandbox code locally and tried and I'm able to run the application smoothly. Steps followed were:

1. Exported as ZIP from provided sandbox link.
2. Ran yarn install  to install all the dependencies.
3. Ran yarn build
4. Ran yarn start 

您可以查看随附的屏幕截图,其中我可以使用服务器文件上提供的凭据登录。

The server file utilises the userDetails json to authenticate. Also the terminal shows the token for reference

For better understanding about the problem and solution you can go through this link below https://www.debuggr.io/react-update-unmounted-component/

Meanwhile, I am trying to fix the problem using a class component approach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM