"this" 在 ember 的 torii-adapter 中未定义

"this" is undefined in torii-adapter in ember

我正在尝试存储一些数据 post 在商店内登录。下面是我的 torii-adapter

的代码
import Ember from 'ember';
import {createToken} from 'myapp/utils/app-utils';

export default Ember.Object.extend({
  store: Ember.inject.service(),

  open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    return new Ember.RSVP.Promise(function(resolve, reject){
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://localhost/getUserInfoWuthAuthCode.php',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then(function(data){
      let user = data.user[0];
      this.set('storage.token',token); //this is undefined
      return {
        user: user
      };
    });
  }

});

我得到的错误是 "TypeError: Cannot read property 'set' of undefined"。 我也在注入商店服务。你能告诉我这里到底出了什么问题吗?

this 未在您当前的上下文中定义。将其分配给另一个变量。

  open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    let that = this;
    return new Ember.RSVP.Promise(function(resolve, reject){
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://localhost/getUserInfoWuthAuthCode.php',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then(function(data){
      let user = data.user[0];
      that.set('storage.token',token); //this is undefined
      return {
        user: user
      };
    });
  }

要进一步了解并查看不同的选项(例如 fat arrowbind 方法),请查看 .

另一种方法是使用 ES6 箭头函数,这样就不需要为 this other 另一个变量赋值。

 open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    let that = this;
    return new Ember.RSVP.Promise((resolve, reject) => {
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://localhost/getUserInfoWuthAuthCode.php',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then((data) => {
      let user = data.user[0];
      that.set('storage.token',token);
      return {
        user: user
      };
    });
  }

Ember-cli 将帮助您将 ES6 转换为 ES5 以使其兼容大多数浏览器。