You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Ember控制器内调用方法报错,排查代码问题

Fixing "this.getValue is not a function" in Your Ember Controller

Hey there! That error almost always comes down to a this context mismatch—let's break down what's going wrong and how to fix it.

Why This Happens

When you try to call this.getValue() inside getResult, the this keyword isn't pointing to your Ember controller instance like you'd expect. The most common triggers are:

  • getResult is being used as a callback (for async operations, DOM events, or even some Ember actions) where the default this context gets overridden.
  • Regular function declarations don't automatically preserve the surrounding this context, so when getResult runs, it's looking for getValue on the wrong object.

Solutions to Try

1. Use an Arrow Function for getResult

Arrow functions capture the this context from their surrounding scope (your controller instance), so this.getValue() will work as intended:

export default Ember.Controller.extend({ 
  // ...
  getValue(){ 
    var a = 7 * 2; 
    return a; 
  }, 
  getResult: () => { 
    var result = this.getValue(); // Now `this` correctly points to the controller
    console.log(result); // Should log 14
  } 
});

2. Explicitly Bind this in the init Hook

If you prefer sticking with regular function declarations, manually bind the controller's context to getResult in the controller's initialization hook:

export default Ember.Controller.extend({ 
  init() {
    this._super(...arguments); // Always call _super first in Ember lifecycle hooks!
    this.getResult = this.getResult.bind(this);
  },

  getValue(){ 
    var a = 7 * 2; 
    return a; 
  }, 
  getResult(){ 
    var result = this.getValue(); 
  } 
});

3. Check How getResult Is Being Invoked

Double-check where getResult is called:

  • If it's used as an Ember template action ({{action 'getResult'}}), modern Ember versions bind actions to the controller by default, but older versions might need explicit context binding.
  • If it's called inside a Promise or setTimeout, wrap it in an arrow function to preserve the controller context:
    fetchData() {
      fetch('/api/data')
        .then(() => {
          this.getResult(); // `this` still references the controller here
        });
    }
    

Quick Debugging Trick

Add console.log(this) at the start of getResult to see what this is actually pointing to. If it logs window, undefined, or another unrelated object instead of your controller, you know the context mismatch is the root issue.

内容的提问来源于stack exchange,提问作者Zaza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:45:41