@vimirtv

Почему возникает ошибка Can't call setState (or forceUpdate) on an unmounted component?

Как избавиться от ошибки в данном случае.
Есть компонент прилоадер, который через три секунды меняется.
Я его отображаю пока не получил ответ от сервера. Спустя три секунды, меняется state этого прилоадера. Но так как ответ уже получен, я его не отображаю.

Прилоадер
export default class LoadingMask extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        togle: false
    }
}

componentDidMount () {
    setTimeout(() => this.setState({togle: true}), 3000)
}


render() {
    return (
      <View>
        {this.state.togle ?
        <View style={{flexDirection: 'row', justifyContent: "center", marginTop: 20,}}>
            <Text style={{marginRight: 20, color: '#4488fe'}} onPress={this.props.action}>Попробовать еще раз?</Text>
            <Ionicons name="md-refresh" size={20} color="#4488fe" />
        </View>
        : <ActivityIndicator size="large" color="#CCC" /> 
        }
      </View>
    )
}

}


Компонент где вызывается прилоадер

import  LoadingMask  from './components/mask_loader'

class Account_list extends Component {
  constructor(props) {
    super(props)
    this.state = {
 loading: true,
}

  componentDidMount = async () => {
   this.setState({
      loading: false
   })
  }

render() {
    return (
      <View style={styles.container}>
{ this.state.loading ? <LoadingMask action={this.fetchData} />  :  <Text>Компонент загружен</Text>
</View>
)
}
  • Вопрос задан
  • 69 просмотров
Решения вопроса 1
Vlad_IT
@Vlad_IT
Front-end разработчик
Запоминайте id таймера, и в методе componentWillUnmount удаляйте таймер через clearTimeout
Будет как-то так

export default class LoadingMask extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        togle: false
    }
    this._timeId = null;
}

componentDidMount () {
    this._timeId = setTimeout(() => this.setState({togle: true}), 3000)
}

componentWillUnmount () {
    clearTimeout(this._timeId);
}

render() {
    return (
      <View>
        {this.state.togle ?
        <View style={{flexDirection: 'row', justifyContent: "center", marginTop: 20,}}>
            <Text style={{marginRight: 20, color: '#4488fe'}} onPress={this.props.action}>Попробовать еще раз?</Text>
            <Ionicons name="md-refresh" size={20} color="#4488fe" />
        </View>
        : <ActivityIndicator size="large" color="#CCC" /> 
        }
      </View>
    )
}

}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы