Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

graphql - React Native - Can't perform a state change on unmounted component error even with isMounted flag

I am working on a React Native project and I have a function that makes a GraphQL query:

 getPosts = async () => {
    const result = await API.graphql(graphqlOperation(listPosts))
    if(this.state.isMounted){
      this.setState({ posts: result.data.Posts.items,
        isLoading: false, isMounted: false})
    }
  }

This function is called in the componentDidMount function. I also have a isMounted field in the state that is initialized to false. At the very top of the componentDidMount function I have:

this.setState({ isMounted: true })

Regardless, I am still getting a warning about trying to set the state on an component that is unmounted. I should also mention that this Component is called from this.props.navigation.navigatecall.

question from:https://stackoverflow.com/questions/65647962/react-native-cant-perform-a-state-change-on-unmounted-component-error-even-wi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why you need the isMounted state? If you are using this state just to be a condition to set the state posts, you could just call the getPosts method inside the componentDidMount function and should work as you expected:

async componentDidMount(){
  await getPosts()
} 

You got it? Waiting for your feedback about my answer. Thx :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...