简体   繁体   English

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

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

I'm getting the error:我收到错误:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined元素类型无效:应为字符串(用于内置组件)或类/函数(用于复合组件)但得到:未定义

With this code:使用此代码:

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;

The problem is that "this" can't be referenced in the catch block for some reason although I'm using arrow functions.问题是尽管我使用箭头函数,但由于某种原因不能在 catch 块中引用“this”。 I've tried binding "this" as well but that didn't work either.我也尝试过绑定“this”,但这也不起作用。 Does anyone have an idea?有人有想法吗?

submitRegistration should not be an arrow function. submitRegistration不应是箭头 function。 By making it an arrow function, it does not have the scope of the Registration class instance.通过使其成为箭头 function,它没有Registration class 实例的 scope。 Change it to a regular method:将其更改为常规方法:


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;

because "this" in the each block of code may have different means and refer to some other parent.因为每个代码块中的“this”可能有不同的含义并引用其他父级。 for solving this problem you have to define a variable in the global scope and make it equal to this.为了解决这个问题,你必须在全局 scope 中定义一个变量并使其等于这个。 then in the rest of the code that variable may be accessible.然后在代码的 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