JavaScript:无法获取回调函数变量且callback报错“不是函数”排查
Hey there, let's break down why you're seeing that frustrating error and how to fix it!
First off, the error callback is not a function tells us one clear thing: when you called the checkNo method, the value passed as callback wasn't actually a function (or maybe nothing was passed at all). That's why even your if (callback) check didn't help—if callback is undefined or null, that condition skips the call, but it doesn't fix the root issue.
Step 1: Fix How You're Calling checkNo
The most common culprit here is how you invoke the checkNo method. Let's look at examples of what's wrong and what's right:
❌ Wrong Calls (These Cause the Error)
// No argument passed at all yourComponent.checkNo(); // Passed a non-function value (string, object, etc.) yourComponent.checkNo("I'm not a function"); yourComponent.checkNo({ someKey: "value" });
✅ Correct Call (Pass a Function)
Make sure you pass an actual function when calling checkNo:
yourComponent.checkNo(function(chkno) { // Do something with the chkno value here console.log("Successfully retrieved chkno:", chkno); });
Step 2: Add a Robust Check for Valid Callback
If there are cases where you might not need to pass a callback, update your checkNo method to handle that gracefully with a type check (not just a truthy check):
checkNo: function (callback) { var comboQuery = Ext.ComponentQuery.query('[name=foocombo]')[0].getSelectedRecord(); var chkno = comboQuery.get('mychkno'); // You confirmed this works, great! // Only call callback if it's actually a function if (typeof callback === 'function') { callback(chkno); } else { // Optional: Add a warning or return the value directly console.warn("checkNo was called without a valid callback function"); return chkno; // Let the caller use the value even if no callback was passed } }
Why Your Original if (callback) Didn't Work
If you called checkNo without any arguments, callback is undefined—which is falsy, so the condition skips the call. But that doesn't fix the fact that you intended to pass a function. The type check typeof callback === 'function' is more reliable because it explicitly verifies that the argument is a function, not just a truthy value.
Quick Double-Check
Just to be thorough: confirm that Ext.ComponentQuery.query('[name=foocombo]')[0] is definitely returning the correct combo component (you said you're getting chkno successfully, so this is probably fine, but it never hurts to verify!).
内容的提问来源于stack exchange,提问作者Nuri Engin

