本文介绍了Apollo mutate 回调中的不变违规设置状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在 catch 子句中使用 this.setState 时,我从事件处理程序中调用了一个 mutate 函数并收到了一个 Invariant Violation 错误.

I'm calling a mutate function from an event handler and getting an Invariant Violation error when I try to use this.setState in the catch clause.

saveToken({data}){
  let {userId, token, expires} = data.login;
  storeLoginToken(userId, token, expires);
  history.push('/dogs');
}
setErrors(error){
  this.setState('error', error.graphQLErrors);
}
handleSubmit(event) {
  event.preventDefault();
  let {email, password} = this.state;
  let {history} = this.props;
  let clientKey = getClientKey();
  this.props.mutate({ variables: { email, password, clientKey } })
    .then(this.saveToken.bind(this))
    .catch(this.setErrors.bind(this))
}

推荐答案

我认为问题在于您错过了 setState 函数内的左括号和右括号.

I think the problem is that you missed the opening and closing brackets inside the setState function.

我会这样写:

class ClassName extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        error,
        ...
      };
      
      this.saveToken = this.saveToken.bind(this);
      this.setErrors = this.setErrors.bind(this)
    }

    ...

    setErrors(error) {
      this.setState({error: error.graphQLErrors}); // should work with brackets
    }
    
  handleSubmit(event) {
    event.preventDefault();
    let { email, password } = this.state;
    let { history } = this.props;
    let clientKey = getClientKey();
    this.props.mutate({
        variables: {
          email,
          password,
          clientKey
        }
      })
      .then(this.saveToken)
      .catch(this.setErrors)
  }

}

这篇关于Apollo mutate 回调中的不变违规设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 01:34