Facundo Quintana
Facundo Quintana

Reputation: 23

Warning: Can't perform a React state update on an unmounted component (multiple components)

REACT NATIVE

I'm using Navigation to move between components equal to this one, only with different ID. Some work and some don't, and react native shows me this warning.

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in "the componentWillUnmount method".

The code of my component:

class MotosbicisScreen extends Component {
  static navigationOptions = {
    title: 'Motos y bicis',
  };
  constructor(props) {
    super(props);

    this.state = {
      data: [],
    };
  }

  componentDidMount() {
    this.getData()
}

getData = async () => {
    const url = 'https://url';
    fetch(url).then((response) => response.json())
    .then((responseJson) =>{
        this.setState({
            data:responseJson
        })
    })
}

  renderRow = ({item}) => {
    if (item.rubroClasificado == 9) {
    if(item.imageJob == null) {
    return(          
      <Card>
      <CardItem>
      <Body>
          <Text>
            {item.Texto} 
            </Text>
            </Body>
            </CardItem>
          </Card>)
    } else {
        img = 'http://url/' +  item.imagepath;
        return(         
            <View style={styles.item}>
            <Image
            source={{ uri: img}}
            width={Dimensions.get('window').width}
            />
            </View>            
            )
    }
  }
} 

  render() {

    return (
      <View style={styles.container}>
          <FlatList style={styles.container}
        data={this.state.data}
        renderItem={this.renderRow}
        keyExtractor={(item, index) => index.toString()} 

        />
    </View>
    );

}
}

Upvotes: 0

Views: 6525

Answers (1)

Mateusz Siniarski
Mateusz Siniarski

Reputation: 1015

It is due to the fact that the Component is calling setState when the component has been dismounted (you have navigated away from the page).

In the past a solution was to track if the component was mounted before setState was called, however this is bad practise.

The following article covers goes over your issue, the old bad practise, and one possible solution. (https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html)

Upvotes: 2

Related Questions