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

GraphQL中在一个mutation内调用另一个mutation的实现及报错解决

问题解答

这个需求完全可行,你遇到的ReferenceError: addAuthor is not defined错误,原因是addAuthor是Mutation对象的属性方法,并非全局可直接调用的函数,代码里直接调用它自然找不到。

修复方案

方案一:抽离公共逻辑(推荐)

把添加作者的核心逻辑抽成独立函数,让两个Mutation方法复用,既解决调用问题,也避免代码冗余:

// 抽离公共的创建作者函数
const createAuthor = (name) => {
  const author = { name, id: uuid() }
  authors = authors.concat(author)
  return author
}

Mutation: {
    addAuthor: (root, args) => {
      return createAuthor(args.name)
    },
    addBook: (root, args) => {
      // 用Array.some()检查作者是否存在,比filter更高效
      const authorExists = authors.some(author => author.name === args.author)
      if (!authorExists) {
        createAuthor(args.author)
      }

      const book = { ...args, id: uuid() }
      books = books.concat(book)
      return book
    }
  }

方案二:直接调用Mutation对象的方法

如果不想抽离函数,也可以直接通过Mutation对象调用addAuthor方法,注意传入对应的参数(这里addAuthor没用到root参数,所以传null即可):

Mutation: {
    addAuthor: (root, args) => {
      const author = { ...args, id: uuid() }
      authors = authors.concat(author)
      return author
    },
    addBook: (root, args) => {
      const authorExists = authors.some(author => author.name === args.author)
      if (!authorExists) {
        // 直接调用Mutation里的addAuthor方法
        Mutation.addAuthor(null, { name: args.author })
      }

      const book = { ...args, id: uuid() }
      books = books.concat(book)
      return book
    }
  }

注:检查作者是否存在时,Array.some()比filter().length > 0更高效,因为some()找到匹配项后会立即停止遍历,无需处理整个数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:45:35