简体   繁体   中英

How to avoid warning: Cannot setState on unmounted component? REACT-NATIVE

im builiding a notebloc, so each time I go to the Edit note screen then go back, this warnings appears, heres the code:

when the app runs, the first component that rendes is Notes:

class Notes extends Component {
    
    state = {
        onpress: false,
        array_notes: [],
        selected_notes: [],
        update: false,
    }

    note = "";
    note_index = "";
    note_number = "";
    item_selected = 0;
    onpress = false;
 
    componentDidMount() {    
        const {navigation} = this.props;
        this._unsubscribe = navigation.addListener("didFocus", () => this.fetch_notes());
    }   
    
    componentWillUnmount() {
        this._unsubscribe.remove();
    }

    fetch_notes = async() => {                  //fetch all the data
        const data = await fetch_notes();
        if (typeof data != "function") {
            this.setState({array_notes: data.array_notes});
        }else {
            data();
        }
    }

as you can see, in the ComponentDidmount() I run the function fetch_data to set the data, heres the fetch_data function :

import AsyncStorage from "@react-native-community/async-storage";

export const fetch_notes = async () => {
    try {
        const data = JSON.parse(await AsyncStorage.getItem("data"));
        if (data != null) {
            return data;
        }else {
            return () => alert("with no data");
        }
    }catch (error) {
        alert(error);
    }
}

here everything works, because its only fetch the data, now when I go to edit note screen and I edit one of the notes, I need to save it, so when I go back I need to fetch the data again so it will update:

save_changes = async() => {
    
    try {
    
        const data = JSON.parse(await AsyncStorage.getItem("data"));
        const index_to_find = this.array_notes.findIndex(obj => obj.note_number === this.note[0].note_number); 
   
        const edited_note = this.note.map((note) => {
            note.content = this.state.content;
            return {...note}
        });
   
        this.array_notes.splice(index_to_find, 1, edited_note[0]);
        data.array_notes = this.array_notes;
        await AsyncStorage.setItem("data", JSON.stringify(data));
     
    }catch(error) {
        alert(error);
    }

when I get back to Notes screen the function runs and works, the data are updated, but the warning still appears, once I saved the edit note and go back, how can I avoid this?

This warning is thrown when you try to set the state of a component after it has unmounted.

Now, some things to point out here

  • The navigation flow, from what have you mentioned is like Notes --> Edit Notes --> Notes . Assuming you are using the StackNavigator from react-navigation , the Notes screen will not unmount when you navigate to Edit Notes screen.
  • The only screen unmounting is Edit Notes when you go back. So you should check the code to verify that you don't have any asynchoronous setState calls in that screen.

PS : The syntax to remove the focus event listener is to just call the returned function as mentioned here . So in your Notes screen inside componentWillUnmount it should be

componentWillUnmount() {
    this._unsubscribe();
}

you need to use componentWillUnmount() function inside the function which you are unmounting.

You can use conditional rendering for mounting or unmounting any componets.

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