axios catch不会捕获错误 [英] axios catch doesn't catch error

查看:485
本文介绍了axios catch不会捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用axios 0.17.0和以下代码:

I'm using axios 0.17.0 with the following code:

this.props.userSignupRequest(this.state)
  .then( res => { console.log(res.data) } )
  .catch( err => { this.setState({ errors: err.response }) } )

并且服务器设置为在未通过用户注册验证时返回400.这也显示在控制台:POST 400 (Bad Request)中,但未执行setState.这是为什么?我也尝试了console.log(err),什么也没做.

And the server is set to return a 400 when user signup validation doesn't pass. That also shows up in console: POST 400 (Bad Request), but the setState is not being executed. Why is that? I also tried console.log(err) and nothing.

推荐答案

可能有一些问题,我们可能需要查看更多代码才能确定.

A few issues could be at play, we'll likely need to see more of your code to know for sure.

Axios 0.17.0将在400响应状态上引发错误.下面的演示显示了这一点.

Axios 0.17.0 will throw an error on the 400 response status. The demo below shows this.

意外的行为可能是由于setState()的异步行为引起的.如果您尝试在调用setState()之后立即console.log的状态,则将无法正常工作.您需要使用setState回调.

The unexpected behavior could be due to the asynchronous behavior of setState(). If you're trying to console.log the state immediately after calling setState() that won't work. You'll need to use the setState callback.

const signinRequest = () => {
  return axios.post('https://httpbin.org/status/400');
}   
  
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      errors: null
    }
  }
  
  handleSignin = () => {
    this.props.userSigninRequest()
      .then(result => {
        console.log(result.status);
      })
      .catch(error => {
        this.setState({
          errors: error.response.status
        }, () => {
          console.error(this.state.errors);
        });
      });
  }
  
  render() {
    return (
      <div>
         <button onClick={this.handleSignin}>Signin</button>
        {this.state.errors}
      </div>
    )
  }
}

ReactDOM.render(<App userSigninRequest={signinRequest} />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js"></script>

<div id="app"></div>

这篇关于axios catch不会捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆