投入新错误时出现未定义的对象(error.response);

时间:2017-12-29 07:58:51

标签: javascript reactjs

我想问一下,当我把它放入throw new Error(error.response)时,为什么我的对象变得不确定但是如果在外面我可以得到确切的值。这是我的代码:

componentDidMount(){
   this.validateUrlInToken()
    .then(this.onValidateUrlInTokenSuccess)
    .catch(this.onValidateUrlInTokenFail);
}

validateUrlInToken() {
  const tokenParams = {
    token: this.props.params.token,
  };

  return axios.post('/api/core/validate_token/', tokenParams);
}

onValidateUrlInTokenSuccess(response) {
  const { data } = response.data;
  const email = data.username;
  const userId = data.user_id;
  const lastLogin = data.last_login;

  this.setState({ email, userId, lastLogin });

  this.getSite()
    .then(this.onGetSiteSuccess)
    .catch(this.onGetSiteFail);
}

onValidateUrlInTokenFail(error) {
  console.log(error.response) // { data: { detail: 'Invalid Token' } }
  this.context.router.push('/login');
  throw new Error(error.response); // Undefined response
}

1 个答案:

答案 0 :(得分:1)

尝试使用回调

onValidateUrlInTokenFail(callback,error) {
  console.log(error.response) // { data: { detail: 'Invalid Token' } }
  this.context.router.push('/login');
  callback(new Error(error.response));
}