【问题标题】:Getting "Invariant Violation" error with Apollo GraphQLApollo GraphQL 出现“不变违规”错误
【发布时间】:2021-02-13 05:37:56
【问题描述】:

我正在使用 Apollo GraphQL,但我是新手,我收到以下错误:

{
    "framesToPop": 1,
    "name": "Invariant Violation"
}

这是我的代码:

const httpLink = createHttpLink({
    uri: "https://api.example.com/v3/ListingsQuery",
    fetch
});
const automaticPersistedQueryLink = createPersistedQueryLink();
const apolloClient = new ApolloClient({
    link: ApolloLink.from([automaticPersistedQueryLink, httpLink]),
    cache: new InMemoryCache()
});
const variables = {
    filters: {statuses: ["ACTIVE", "UNLISTED"]},
    orderBys: [{sortField: "STATUS", sortOrder: "DESC"}],
    shouldFetchHostMultiListingAgendaPermissions: true,
    offset: 0,
    shouldFetchListingPermissions: false,
    count: 15,
    query: null
};
await apolloClient.query({
    query: {},
    variables
});

知道我做错了什么吗?

【问题讨论】:

  • “Invariant Violation”消息后没有数字?对此不确定(我本人对 Apollo 比较陌生),但我认为自 Apollo Client 3.1.0 以来,在 Invariant Violation 消息之后应该总是有一个数字。您是否有可能使用的是旧版本的库?

标签: apollo


【解决方案1】:

首先,Apollo 似乎是以“生产模式”而不是“开发模式”启动的。通过在开发模式下启动它,Apollo 将为您提供更详细的错误消息。要解决此问题,请将env.NODE_ENV 设置为development 来启动您的节点进程。抱歉,如果不清楚,但我在这里不能更准确,因为确切的过程取决于您的应用程序的启动方式和/或您使用的框架......

不过,在最近的版本中,在生产模式下运行时,错误消息中应该有一个数字错误代码,例如 Invariant Violation: 42。这些数字错误代码使诊断问题变得更加容易,即使在生产模式下也是如此。确保您使用的是最新版本的 @apollo/client(在我撰写本文时,最新版本是 3.2.5;请参阅 https://www.npmjs.com/package/@apollo/client)。

现在,关于错误本身......完整的错误消息很可能是Invariant Violation: You must wrap the query string in a "gql" tag. 这是由于您提供了一个空查询,如下所示:

await apolloClient.query({
    query: {},   // <--- Empty query here
    variables
});

有几种方法可以向 Apollo 客户端提供查询。最简单的方法是将 GraphQL 查询嵌入到 JavaScript 源代码中,使用“gql 标签”表示法,例如:

await apolloClient.query({
    query: gql`
      query TestQuery {
        launch(id: 56) {
          id
          mission {
            name
          }
        }
      }
    `,
    variables
});

这应该是开箱即用的,但出于性能原因,您应该在构建过程中添加一个 GraphQL 编译步骤。也许这个过程已经到位(例如,如果您使用 Create React Apps 或 Gatsby 等框架开始您的项目......)。有关此问题的说明,请参阅此文档 (https://www.apollographql.com/docs/react/performance/babel/)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-18
    • 2020-12-11
    • 2019-07-05
    • 1970-01-01
    • 2015-11-14
    • 2019-08-16
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多