Node.js Uncaught TypeError:callback不是process.nextTick中的函数

我收到以下错误。 这显然来自传递给process.nextTick的callback。 鉴于堆栈跟踪几乎不可用,我该如何debugging? 幕后发生了什么,如何在一个更大的项目中解决这个问题?

 TypeError: callback is not a function at nextTickCallbackWith0Args (node.js:420:9) at process._tickDomainCallback (node.js:390:13) 

NB老版本的Node有不同的process.nextTick实现,并且吐出下面的堆栈跟踪。

 Uncaught TypeError: undefined is not a function at process._tickCallback (node.js:415:13) 

Node.js如果你传递给process.nextTick的函数在tick过去之后不是一个函数,而不是在你第一次调用它的时候告诉你,那么Node.js的tickcallback就更好。

如果函数在打勾后被调用:

 // this will print "hi!", followed by "hello there" process.nextTick(function() { console.log('hello there'); }); console.log('hi!'); 

一个非函数直到下一个刻度才会真正重要:

 // this will just print "hi!", and an error will be thrown later on process.nextTick(undefined); console.log('hi!'); 

下面,我将概述两种可以用来追踪罪魁祸首的诊断工具。

工具1: longjohn

事实certificate,这种场景已经足够普遍,存在一个工具来扩展堆栈跟踪与来自以前的滴答信息。

只需安装longjohn ( 在npm上可用),并在您的stream程启动时require 。 这将产生类似于以下的堆栈跟踪:

 TypeError: Cannot read property 'apply' of undefined at nextTickCallbackWith0Args (node.js:420:9) at process._tickCallback (node.js:349:13) at Function.Module.runMain (module.js:443:11) at startup (node.js:139:18) at node.js:968:3 --------------------------------------------- at Object.<anonymous> (.../example.js:3:9) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:968:3 

现在你已经有了一个有用的堆栈跟踪,你可以使用你的debugging技巧来弄清楚你为什么给process.nextTick未定义,而不是一个函数。

猴子补丁

因为javascript是dynamic的,所以我们可以很容易地设置一个新的版本的process.nextTick (也就是我们可以修补它)跟踪它的调用,但代理真正的nextTick函数:

 var nextTick = process.nextTick; process.nextTick = function(callback) { if (typeof callback !== 'function') { console.trace(typeof callback + ' is not a function'); } return nextTick.apply(process, arguments); }; 

注意:我不build议在生产代码中这样做,但是确实可以更容易地find除process.nextTick之外的其他function。 请记住,这是修改全局processvariables,所以它可能在某个时候被打破,这当然不被认为是最好的做法,但它会很好地find小问题。 (附录:自从我写这篇文章以来,我不得不修改它,因为它打破了一次。)

 Trace: undefined is not a function at process.nextTick (.../example.js:5:13) at Object.<anonymous> (.../example.js:10:9) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:968:3 

如上所述,现在您已经有了一个有用的堆栈跟踪,可以确定根本原因。

就内部而言,请查看源代码 ( 旧链接 )中的node.js中的 _tickCallback函数。