求助:Ember控制器内调用方法报错,排查代码问题
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:
getResultis being used as a callback (for async operations, DOM events, or even some Ember actions) where the defaultthiscontext gets overridden.- Regular function declarations don't automatically preserve the surrounding
thiscontext, so whengetResultruns, it's looking forgetValueon 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

