Search code examples
javascriptreactjses6-promisecancellation

React.js tells you to cancel promises. Official Promises can't be cancelled. What am I supposed to do instead?


In order to prevent phantom updates to an unmounted React component, React tells you to cancel any pending promises on a component (such as promises for fetching additional data) when it unmounts. This is very easy to accomplish with Bluebird promises, which have a .cancel() method on them that causes the .then() and .catch() handlers to never respond.

However, ES6 Promises do not support cancellation. In addition, ES7's async and await only use native Promises and do not support any drop-in replacements (such as Bluebird). This means that if you want to be able to cancel Promises in React, as they tell you to do, you have to use .then() and .catch() and also have to place a middleman on native Promise methods like fetch() so that it can be cancelled.

Is this really what React expects?


Solution

  • The latest React docs (Aug 2023), suggest 2 solutions to this issue:

    1. Create a new 'ignore' variable that is set to true during the Effect cleanup. When the Promise returns, ignore the result based on the variable.

    2. Use the AbortController API to cancel the asynchronous action.

    Check the solution to 'Challenge 4 of 4' on this page of the React Docs.