【问题标题】:axios catch doesn't catch erroraxios catch 不捕获错误
【发布时间】:2018-04-19 03:47:05
【问题描述】:

我正在使用axios 0.17.0,代码如下:

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),什么也没有。

【问题讨论】:

  • 你能告诉我们userSignupRequest的内容吗?
  • 是什么让你认为setState() 没有被执行?

标签: reactjs redux axios


【解决方案1】:

POST 400 (Bad Request) 不是错误,而是不成功的响应。 catch 在请求出错时触发。

如果你想捕捉400或类似的HTTP错误,你需要检查status

示例

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

【讨论】:

    【解决方案2】:

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

    Axios 0.17.0 将在 400 响应状态上抛出错误。下面的演示显示了这一点。

    意外行为可能是由于 setState() 的异步行为造成的。如果您在调用setState() 后立即尝试console.log 状态,那将不起作用。您需要使用 setState 回调。

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-21
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多