Search code examples
javascriptreactjssetstate

React updating unmounted component


so I have this function that fetches playlist from my API and after that updates the state.

My problem is that if I change the route while the API is still fetching data, it will try to update the component even if it is not mounted anymore. This results in the following console error:

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

I would like to know what are the best practices to avoid this kind of conflict.

Thanks in advance for your answers!

  async getUserPlaylists() {
    let data = await request({ path: '/playlists' });
    data = data || [];

    const sanitizedPlaylists = data.map((item, index) => ({
      key: index,
      name: item.name,
      imageUrl: item.imageUrl,
      ...item,
    }));

    this.setState({
      playlists: sanitizedPlaylists,
      loadingPlaylists: false,
      submitting: false,
    });

    return request.data;
  }


Solution

  • You can try aborting the request in componentWillUnmount which should cause the Promise not to get resolved:

    this.request = request({ path: '/playlists' });
    let data = await this.request;
    
    componentWillUnmount() {
      if (this.request) this.request.abort();
    }
    

    Alternatively just set a flag:

    componentWillUnmount() {
      this.unmounted = true;
    }
    

    And check it before calling setState:

    if (this.unmounted) return;
    this.setState(...)
    

    Though all these might be unnecessary complication. You can just ignore the warning in development.