首页 > 解决方案 > 错误:未捕获(在承诺中)类型错误:_this2.next 不是 reactJS 中的函数

问题描述

我收到了这个错误你能帮我删除这个错误吗?我的申请中有 4 个案例。您可以查看我的第 2 步代码以防万一。请帮助我,我真的被卡住了

case 1:
        // code run for step 2

        const reader = new FileReader();
        const storeUser = JSON.parse(localStorage.getItem('user'));
        reader.onload = function(upload) {
          fetch(`...../api/s3/uploadtoaws`, {
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            method: 'POST',
            body: JSON.stringify({
              userId: storeUser._id,
              type: 'employee',
              content: upload.target.result,
              key: 'e.file.name',
              oldKey: '',
            }),
          })
            .then(response => response.json())
            .then(res => {
              if (res.error) {
                console.warn(res);
              } else {
                console.warn(res);
                this.next();
              }
            })
            .done();
        };
        reader.readAsDataURL(values.picture.file.originFileObj);
        break;

标签: javascriptreactjsecmascript-6

解决方案


reader.onload = 功能(上传){

由于这是一个普通函数,它的值this取决于它的调用方式。我假设 FileReader 调用它this等于全局对象(在非严格模式下)或未定义(在严格模式下)。虽然由于我不确定 FileReader 代码是如何实现的,但它可能this等同于其他东西,例如文件阅读器本身。无论哪种方式,稍后当您调用 时this.nextthis都不等于您认为的那样。

如果将其更改为箭头函数,它将this从其定义的位置获取其值。

reader.onload = (upload) => {

请注意,这可能还不够,因为它还取决于您提供的示例周围的代码。您可能需要将其他函数转换为箭头函数,和/或使用function.prototype.bind


推荐阅读