尝试将函数传递给axios.then并接收时接收到错误

时间:2018-12-10 20:30:23

标签: javascript reactjs axios

axios.post('http://localhost:3000/api/v1/login', {
                email: this.state.email,
                password: this.state.password
            }, {
                    headers: {
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Credentials": true,
                        "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT,DELETE",
                        "Access-Control-Allow-Headers": "",
                    }
                })
                .then(function (response) { this.onloginSuccess(response) })
                .catch(function (error) { this.onLoginFail(error)});

我有一个此axios帖子,假定该帖子可以处理以下响应:

onloginSuccess = (response) => {
        console.log(response)
        this.setState({
            buttonDisable: false
        });

        sessionStorage.setItem('uuid', response.value.data.uuid)
        sessionStorage.setItem('bearertoken', response.value.data.bearertoken)


        this.props.history.push({ pathname: '/dashboard' })
    }

以及以下错误:

onloginFail = (error) => {
        NotificationManager.error(error.response.data.message, 'Error!', 5000);
        this.setState({
            buttonDisable: false
        });
    }

我保留以下错误:

Uncaught (in promise) TypeError: Cannot read property 'onLoginFail' of undefined
    at eval (index.js?8a7d:95)

当我删除onLoginFail时,我得到

index.js?8a7d:94 Uncaught (in promise) TypeError: Cannot read property 'onloginSuccess' of undefined
    at eval (index.js?8a7d:94)

1 个答案:

答案 0 :(得分:1)

.then(function (response) { this.onloginSuccess(response) })

将其更改为箭头功能。

.then((response) => this.onloginSuccess(response))

常规函数根据其调用方式获得其this的值。该函数在没有特定上下文的情况下被调用,因此this被设置为窗口对象(在非严格模式下)或未定义(在严格模式下,您似乎在其中)。另一方面,箭头函数从定义的地方获得其this的值,因此this将等于您调用axios.post时的值。

或者,由于onLoginSuccess本身是一个箭头函数,并且参数已经按照正确的顺序排列,因此您可以将引用传递给onLoginSuccess:

.then(this.onloginSuccess)