[英]TypeError: functionName is not a function but I've defined it as a function
这是错误:
logPunishment(target.id, logObj)
^
TypeError: logPunishment is not a function
代码:bot/components/ban.js
const { logPunishment } = require('../db.js')
logPunishment(input1, input2)
一些代码:bot/db.js:
async function logPunishment(userId, punishmentObject){
data = await User.findOne({id: userId})
if (!data){
await User.create({id: userId, punishments: []})
data = await User.findOne({id: userId})
}
punishments = data.punishments
punishments.push(punishmentObject)
User.updateOne({id: userId, punishments: punishments})
}
module.exports.logPunishment = logPunishment
logPunishment明明是函数,为什么说不是函数呢? 在 console.log(logPunishment) 这是结果:
undefined
为什么我不明白。 请帮忙? 我现在可以做些什么来修复它? 除了这个之外没有其他错误(目前)请有人帮忙!!! 我已经按照答案试过了
const logPunishment = require('../db.js').logPunishment,
这不起作用另外我在运行程序后收到此警告:
(node:40712) Warning: Accessing non-existent property 'logPunishment' of module exports inside circular dependency
我没有覆盖任何出口,我已经证实了这一点。
TL;DR 这是因为你的循环依赖。 考虑同一目录中的以下两个文件:
一个.js
const { b } = require('./b');
module.exports.a = 'hello world';
console.log(b());
和 b.js
const { a } = require('./a.js');
function b() {
return a;
}
module.exports.b = b;
如果你运行node a.js
你会看到循环依赖错误
(节点:9235)警告:在循环依赖中访问模块导出的不存在的属性“a”
如果你运行node b.js
你会看到
TypeError: b 不是一个函数
这与当存在循环依赖时如何解决require
有关。 如果你运行a
那么它需要b
而它需要a
这意味着b
得到a
的未完成导出,所以你会看到undefined
print 而不是 hello world。 如果你运行b
你会在a
中得到b
的未完成导出,这意味着你将调用undefined
作为函数
您可以通过将b
需要的东西从a
移动到另一个文件来修复它:使用循环依赖关系并不是一个很好的理由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.