Getting wierd Uncaught TypeError: this._saveFile is not a function with es6

Getting wierd Uncaught TypeError: this._saveFile is not a function with es6

我在 es6 中遇到了一个奇怪的错误。 "this" 值不是

应该是,它阻止我在

中调用 this._saveFile()

下面的代码。

    /**
     * Performs the actions for saving the file.
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
  _saveFile(data){

      var p = new Promise((resolve,reject) => {
        if(!isStream.readable(data.stream)){
          reject("Data object must have a stream property that is a readable stream");
        }
        else if(typeof data.fileName !== 'string'){
          reject("The fileName property is missing or malformed in the data object");
        }
        else{
          let pool = ConnectionPool.getInstance();
          pool.getConnection((err,conn) => {
            if(err){

              reject(err);
            }

            let m = new HackFileMapper(conn);
            let dc = new DataConverter();
            dc.streamToBase64(data.stream)
            .then(base64Data => {
              m.saveFile({
                fileName:data.fileName,
                fileData:base64Data
              },{
                sharerId:data.fields.sharerId,
                shareeId:data.fields.shareeId
              })
              .then(fileId => {
                conn.release();
                resolve(fileId);
              });
            }).catch(reason => {
              conn.release();
              reject(reason);
            });
          });

        }

      });
      return p;
    };




  /**
   * Tries to handle the request as a save file request.
   * If it can't then it passes the request to the
   * next one in the chain.
   *
   * @param  {[type]} request  [description]
   * @param  {[type]} response [description]
   * @return {boolean}  True if the request was handled successfully,
   *  either by this handler or a handler further along the chain.
   */
  handle(request, response){

    var self = this;

    var p = new Promise((resolve,reject) => {

      if(typeof request === 'undefined' || request === null){

          reject("The handle function must be passed a valid Request and Response object.");
      }
      else{ // try and process it.

        var contentType = request.headers['content-type'];
        if(contentType !== null &&
          typeof contentType !== 'undefined' &&
          contentType.indexOf('multipart/form-data') === 0){ // can it do it?

            // handle it here.
            parseFormdata(request,(err,data) => {

              if(err){
                SaveFileHandler._send400Response(response,"an error occurred parsing the forma data");
              }
              else if(data.parts.length < 1){
                SaveFileHandler._send400Response(response,"No files sent");
              }
              else if(!data.fields.supplierId || !data.fields.customerId){
                SaveFileHandler._send400Response(response,"supplerId and customerId must be included.");

              }else{
                this._saveFile(data).then(fileId => {
                  ConnectionPool.getInstance().getConnection((err,conn) => {
                    var m = new HackFileMapper(conn);
                    m.loadIcon(fileId).
                    then(icon => {

                      response.setHeader('content-type', 'application/json');
                      response.statusCode = 200;
                      response.end(JSON.stringify(icon));
                      resolve(true);

                    });
                  });

                }).
                catch(reason => {
                  SaveFileHandler._send400Response(response,reason);
                });
              }
            });
        }
        else{ // pass it on.

            self.successor.handle(request,response)
            .then(result => resolve(result))
            .catch(reason => reject(reason)); // for testing purposes.
        }

      } // else

    });
    return p;
  }; // end fn.

当我 运行 使用 npm test 时,我得到:

Uncaught TypeError: this._saveFile is not a function
      at parseFormdata (src/request_handlers/SaveFileHandler.js:114:22)
      at exports.Dispenser.internals.Dispenser.<anonymous> (node_modules/parse-formdata/index.js:43:20)

我试着把 "this" 放在函数前面并存储一个

将 "this" 引用为 "self" 并且出现相同的问题。

console.log(self) 打印出与此完全无关的信息

class。不是异步问题,肯定是别的问题。

handle 中,您的箭头函数都正确地从外部块继承了 this,这意味着如果 this._saveFile 在嵌套块中没有被正确引用, this 不引用 handle 顶层的实例化对象。当您将函数作为回调传递而没有显式 bind 将其传递给预期的调用上下文时,就会发生这种情况,例如:

var server = new HttpServer(handler.handle);

在这里,您将 handle 函数传递给构造函数,但是 没有 handler 的调用上下文,这意味着当 HttpServer 调用回调,其 this 不再引用 handler.

const handler = {
  handlerProp: 'handlerProp',
  handle() {
    console.log(this.handlerProp);
  }
};
function invoker(callback) {
  callback();
}

// Works:
handler.handle();

// Doesn't work:
invoker(handler.handle);

一种选择是使用 .bind 来确保调用回调时,调用上下文符合预期:

var server = new HttpServer(handler.handle.bind(handler));

另一种选择是传递一个 调用 handler.handle 的函数,具有适当的调用上下文:

var server = new HttpServer(() => handler.handle());

const handler = {
  handlerProp: 'handlerProp',
  handle() {
    console.log(this.handlerProp);
  }
};
function invoker(callback) {
  callback();
}

// Fixed:
invoker(handler.handle.bind(handler));

// or:
invoker(() => handler.handle());