'警告:无法对未挂载的组件执行 React 状态更新。这是无操作,但它表示应用程序中存在内存泄漏



>im 构建一个 react 本机应用程序,但我仍然有 2 个屏幕 1.进入手机 2.验证一次性密码

输入用户信息.js

class UserInfoInput extends Component {
constructor(props) {
super(props);
this.state = { formValid:true,
validMobileNumber:false,
.
.}}

componentWillReceiveProps(nextProps) {
if(nextProps.common.isFetching===false) {
this.props.navigation.navigate('VerifyOtpScreen')
.
.
} else {
this.setState({isLoading:true})
}} 
onPressNext=()=> {
this.props.sendOtp(payload)}
render() {
return (<View/>) 
}
}

}
function mapStateToProps(state) {
return {
common: state.common
}
}
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({ sendOtp }, dispatch)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(UserInfoInput);

在这里用户输入电话号码,并触发一个动作sendOtp,响应将在化简器中,它将在组件将接收eveprops()生命周期中可用。

验证Otp.js

class VerifyOtp extends Component {
constructor(props) {
super(props);
this.state = { oneTimePIN: '' ,
.};
}
componentDidMount(){
this.setState({ phoneNumber:this.props.common.phone});
}
componentWillMount() {
setTimeout(() => {
this.setState({ isResendDisabled: false, opacity: 1 });
}, 30000);
}
componentWillReceiveProps(nextProps){
//do operation 
}
onPressNext=()=>{
if(this.state.oneTimePIN=='') {
this.setState({showNotification:true})
} 
else {
this.onSubmit()
}
}
onSubmit=()=>{
this.props.verifyOtp(payload) 
}
onResendOtp=()=>{
this.props.sendOtp(payload,locationData) 
this.setState({ isResendDisabled: true, opacity: 0.5 });
setTimeout(() => {
this.setState({ isResendDisabled: false, opacity: 1 });
}, 30000);
}
render() {
return (<View><Elements></View>)
}
}
function mapStateToProps(state) {
return {
common: state.common
}
}
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({ verifyOtp,sendOtp }, dispatch)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(VerifyOtp);
VerifyOtp screen used to verify the otp.

问题是,如果我移回进入用户信息屏幕并再次移动到验证OTP屏幕,我会收到警告消息

'警告:无法对未挂载的组件执行 React 状态更新。这是无操作,但它表示应用程序中存在内存泄漏 警告的原因是什么,以及如何解决这个问题?

当您调用异步函数后跟 setstate 时,会发生这种情况。 一个简单的解决方法是这样的:

constructor(props) {
this.state = {
...
this.isCancelled: false
}
}
componentWillMount() {
setTimeout(() => {
!this.state.isCancelled && this.setState({ isResendDisabled: false, 
opacity: 1 });
}, 30000);
}

并在componentWillUnmount

componentWillUnmount() {
// setting it true to avoid setState waring since componentWillMount is async
this.state.isCancelled = true;
}

最新更新