ReactJS: When should setState be installed using isMounted?

The documentation for the Replyjs isMounted states that:

You can use this method to protect asynchronous calls to setState() or forceUpdate() .

My main question is: when should call setState() protected by calling isMounted() ?

The AJAX Basic Tutorial http://facebook.imtqy.com/react/tips/initial-ajax.html setState used in the XHR callback uses the isMounted() protector, but is this required?

Second question: if required, why is this so? It seems that the test itself is very simple and can be built into setState() without any significant performance setState() , but with great simplification in using the API.

+6
source share
1 answer

Logically, isMounted is needed if the component can be unmounted when calling the callback.

Best practice is to avoid this in componentWillUnmount, for example. aborting an ajax request, canceling a timeout, or unsubscribing from an event.

Perhaps the api is simpler because setState does not fail if it is called at the wrong time. With a silent failure, many errors occur that are difficult to track.

+4
source

Source: https://habr.com/ru/post/977926/


All Articles