ncaught TypeError:无法读取未定义的属性''

时间:2019-09-04 12:36:51

标签: javascript reactjs

我正在尝试使用react向网页添加一个复选框。其值在useWalletCreadit中。之后,通过提交表单,它应该将其发布到api.py文件中。这是发布方法:

submitForm: (pay_method, useWalletCredit, onSuccess, onFailure) => {
    console.log(this.useWalletCredit);
    dispatch({type: 'START_LOADING'});
    return PrivateApi.post('cart/pay', {
        'submit-pay': 'submit',
        web: 'true',
        'pay-method': pay_method,
        'useWalletCredit_': this.useWalletCredit,
    })
        .then(res => {
            dispatch({type: 'END_LOADING'});
            if (onSuccess) onSuccess(res.data);
        }).catch(error => {
            dispatch({type: 'END_LOADING'});
            if (onFailure) onFailure(error);
        })
},

它会引发此错误:

  

CartPay.js:532未捕获的TypeError:无法读取未定义的属性'useWalletCredit'

2 个答案:

答案 0 :(得分:0)

如果这是组件/类,并且具有箭头功能,则this将为undefined,因为将没有要使用的父上下文。

使用正常功能:

submitForm: function(pay_method, useWalletCredit, onSuccess, onFailure) {
   ...
}

答案 1 :(得分:0)

您正在使用箭头功能。箭头函数不会创建自己的this对象,而是从其外部范围继承。

(对于我来说,没有进一步的上下文)您没有任何this对象也很奇怪,因为我希望useWalletCredit的值为{{1} }。

尽管您可以直接直接引用undefined,但您不必遇到这个问题。