简体   繁体   中英

“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. I've tried binding "this" as well but that didn't work either. Does anyone have an idea?

submitRegistration should not be an arrow function. By making it an arrow function, it does not have the scope of the Registration class instance. 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. for solving this problem you have to define a variable in the global scope and make it equal to this. then in the rest of the code that variable may be accessible.

    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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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