gpt4 book ai didi

javascript - setState 只能更新一个已挂载或挂载的组件

转载 作者:行者123 更新时间:2023-11-30 11:36:49 24 4
gpt4 key购买 nike

我有一个登录组件,当用户提交登录表单时,我得到一个错误

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

我什至找不到这个错误在哪里

class LoginForm extends React.Component {
state = {
identifier: '',
password: '',
errors: {},
isLoading: false
};

static contextTypes = {
router: PropTypes.object.isRequired
};

isValid = () => {
const { errors, isValid } = validateInput(this.state);
if (!isValid) {
this.setState({ errors });
}
return isValid;
};

onSubmit = (e) => {
e.preventDefault();
if (this.isValid()) {
this.setState({ errors: {}, isLoading: true });
const loginDetails = Object.assign({}, {identifier: this.state.identifier, password: this.state.password});
this.props.login(loginDetails).then(res => {
console.log('res', res);
return this.context.router.push('/');
}).catch(error => {
return this.setState(Object.assign({}, this.state, error, {isLoading: false}));
});
}
};

onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};

render() {
const { errors, identifier, password, isLoading } = this.state;
return (
<form onSubmit={this.onSubmit}>
<fieldset>
<legend>Login</legend>
{ errors.form && <div className="alert alert-danger">{errors.form}</div> }
<TextFieldGroup
name="identifier"
label="Username / Email"
value={identifier}
error={errors.identifier}
onChange={this.onChange}
/>
<TextFieldGroup
name="password"
label="Password"
value={password}
error={errors.password}
onChange={this.onChange}
type="password"
/>
<div className="form-group">
<button className="btn btn-primary btn-lg" disabled={isLoading}>Login</button>
</div>
</fieldset>
</form>
);
}
}

export default connect(null, { login })(LoginForm);

具体错误在哪里?

最佳答案

您正在使用该 promise 调用运行此异步代码:

onSubmit = (e) => {
e.preventDefault();
if (this.isValid()) {
this.setState({ errors: {}, isLoading: true });
const loginDetails = Object.assign({}, {identifier: this.state.identifier, password: this.state.password});
this.props.login(loginDetails).then(res => {
console.log('res', res);
return this.context.router.push('/');
}).catch(error => {
return this.setState(Object.assign({}, this.state, error, {isLoading: false}));
});
}
};

所以每当 promise 失败时,它都会调用 setState。即使您的组件不再安装,此代码也会运行。

这里有一些文档和建议来解决 promise 问题 https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html

this library似乎用装饰器包装 promise - 我不是建议您使用它,它只是了解正在发生的事情的好方法。

顺便说一句,这是使用 redux 的一个很好的理由.

关于javascript - setState 只能更新一个已挂载或挂载的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44103590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com