Search code examples
react-nativefluxsetstate

React Native - setState Warning on second mount


please check the follow code:

componentDidMount() {
    /*
     * Add listener
     * The User has search for a team
     */
    teamStore.addChangeListener("SEARCH_TEAMS", this.updateTeams.bind(this));
}

componentWillUnmount() {
    /*
     * Remove Listener and clear the Store
     */
    teamStore.removeChangeListener("SEARCH_TEAMS", this.updateTeams);
    teamStore.resetTeams();
}

/*
 * The API has find some new teams
 * Update the state and show the new teams in the listview
 */

updateTeams() {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.setState({dataSource: ds.cloneWithRows(teamStore.getAllTeams())});
}

Info: The SEARCH_TEAMS Event is triggered by another Component.

If I render the component first times everything works fine. But if I pop the page and navigate again on this page I got this warning:

Warning: setState(…) can only update a mounted or mounting component…


Solution

  • You didn't properly clear your event listener, since different function references were given. This makes your event listener to keep listening and setState is called in it.

    Here's a fix:

    componentDidMount() {
        // Save the function you want to listen with so you can remove it later
        this.updateTeamsBound = this.updateTeams.bind(this);
        teamStore.addChangeListener("SEARCH_TEAMS", this.updateTeamsBound);
    }
    
    componentWillUnmount() {
        teamStore.removeChangeListener("SEARCH_TEAMS", this.updateTeamsBound);
        teamStore.resetTeams();
    }