React 无法读取 属性 setState of undefined in .then() 即使使用箭头函数

React Cannot read property setState of undefined in .then() even using arrow function

不确定我做错了什么。我知道我无法访问正确的 this,但我认为使用箭头函数可以解决这个问题。我的 console.log(this) returns 未定义。

handleSubmit(event) {
    event.preventDefault();
    const formData = {
        username: event.target.username.value,
        password: event.target.password.value
    }
    fetch('http://localhost:4000/user/login', {
        method: "POST",
        mode: "cors",
        body: JSON.stringify(formData),
        headers: {
            "Content-Type": "application/json"
        }
    })
    .then((res) => res.json())
    .then((res) => {
        if(res.token == undefined) {
            console.log(this)
            this.setState({ logFailureMsg: res.message })
        } else {
            localStorage.setItem('authorization', `Bearer ${res.token}`);
        }

    })
    .catch(err => console.error(err)) 
}

这不是箭头函数。将您的函数更改为如下所示:

handleSubmit = event => {
    // your code...
}

还有,记得把你的函数调用成this.handleSubmit,否则this不会被绑定。