繁体   English   中英

尽管有箭头功能,但在 axios 中未定义“this”

[英]“this” undefined in axios catch block despite arrow functions

我收到错误:

元素类型无效:应为字符串(用于内置组件)或类/函数(用于复合组件)但得到:未定义

使用此代码:

class Registration extends React.Component {

  state = {...}

  submitRegistration = e => {
      let registration = {...}

      Axios.post('/registration', registration)
        .then(res => {
          console.log("Successfully sent registration data", res)
        })
        .catch(() => {
          this.setState({ showNoServerConnectionAlert: true })
        });
    }
    e.preventDefault()
  }

  render() {
    return (
      ...
    )
  }

export default Registration;

问题是尽管我使用箭头函数,但由于某种原因不能在 catch 块中引用“this”。 我也尝试过绑定“this”,但这也不起作用。 有人有想法吗?

submitRegistration不应是箭头 function。 通过使其成为箭头 function,它没有Registration class 实例的 scope。 将其更改为常规方法:


class Registration extends React.Component {

  state = {...}

  submitRegistration(e) {
      let registration = {...}

      Axios.post('/registration', registration)
        .then(res => {
          console.log("Successfully sent registration data", res)
        })
        .catch(() => {
          this.setState({ showNoServerConnectionAlert: true })
        });
    }
    e.preventDefault()
  }

  render() {
    return (
      ...
    )
  }

export default Registration;

因为每个代码块中的“this”可能有不同的含义并引用其他父级。 为了解决这个问题,你必须在全局 scope 中定义一个变量并使其等于这个。 然后在代码的 rest 中,该变量可能是可访问的。

    class Registration extends React.Component {
       state = {...}
       submitRegistration = e => {
      let registration = {...}
      var sellf = this;

      Axios.post('/registration', registration)
        .then(res => {
          console.log("Successfully sent registration data", res)
        })
        .catch(() => {
          sellf.setState({ showNoServerConnectionAlert: true })
        });
    }
    e.preventDefault()
  }

  render() {
    return (
      ...
    )
  }
export default Registration;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM