2017-03-02 116 views
2

我需要在我的组件超时内的setState,所以我这样做:阵营:的setState只能更新安装或安装组件

componentDidMount() { 
    this.timeouts.push(setTimeout(() => { 
    this.setState({ text: 2 }); 
    }, 4000)); 
} 

componentWillUnmount() { 
    this.timeouts = []; 
} 

但我发现了这个错误:

Warning: setState(...): Can only update a mounted or mounting component. 
This usually means you called setState() on an unmounted component. 
This is a no-op. 

我在做什么错?

+0

致电前的setState您的组件将被安装,但您的组件没有安装该组件已安装后 –

+0

@IhorSkliar componentDidMount被调用,在componentDidMount功能,所以设置状态不会是一个问题 –

+0

@IhorSkliar我” m使用内部componentDidMount,因此它被挂载。 –

回答

6

更改您的componentWillUnmount以正确清除超时。您需要使用clearTimeout清除超时而不是清空数组。

componentDidMount() { 
    this.timeouts.push(setTimeout(() => { 
    this.setState({ text: 2 }); 
    }, 4000)); 
} 

clearTimeouts: function() { 
    this.timeouts.forEach(clearTimeout); 
} 

componentWillUnmount() { 
    this.clearTimeouts(); 
} 
相关问题