React 和 ApolloClient:网络错误:forward(...).subscribe 不是函数
Posted
技术标签:
【中文标题】React 和 ApolloClient:网络错误:forward(...).subscribe 不是函数【英文标题】:React and ApolloClient: Network error: forward(...).subscribe is not a function 【发布时间】:2018-11-10 18:37:32 【问题描述】:我正在构建一个 React + GraphQL 应用程序并遇到一个奇怪的问题。下面的代码设置了一个 ApolloClient,添加了一个不记名令牌,然后尝试通过 id 获取。
async componentDidMount()
const id = this.props.match.params.id;
if (id !== 'new')
const authLink = setContext(async (_, headers) =>
const token = await this.props.auth.getAccessToken();
// return the headers to the context so httpLink can read them
return
headers:
...headers,
authorization: token ? `Bearer $token` : ''
);
const client = new ApolloClient(
link: authLink.concat(httpLink),
cache: new InMemoryCache()
);
client.query(
query: gql`
query GetPoints(id: Int)
pointsGet(id: $id)
date,
alcohol,
exercise,
diet,
notes
`,
variables: id: id
)
.then(result =>
console.log(result);
this.setState(points: result.data.points);
);
else
console.log('new!');
此代码导致以下错误:
Uncaught (in promise) Error: Network error: forward(...).subscribe is not a function
at new ApolloError (ApolloError.js:43)
at QueryManager.js:327
at QueryManager.js:762
at Array.forEach (<anonymous>)
at QueryManager.js:761
at Map.forEach (<anonymous>)
at QueryManager../node_modules/apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (QueryManager.js:754)
at QueryManager.js:254
这是我运行良好的代码(不带参数):
async componentDidMount()
const user = await this.props.auth.getUser();
this.setState(user);
const authLink = setContext(async (_, headers ) =>
const token = await this.props.auth.getAccessToken();
// return the headers to the context so httpLink can read them
return
headers:
...headers,
authorization: token ? `Bearer $token` : '',
'x-forwarded-user': user ? JSON.stringify(user) : ''
);
const client = new ApolloClient(
link: authLink.concat(httpLink),
cache: new InMemoryCache()
);
client.query(
query: gql`
points
id,
user
id,
lastName
date,
alcohol,
exercise,
diet,
notes
`
)
.then(result =>
console.log(result);
this.setState(points: result.data.points);
);
这是我正在使用的库列表:
import ApolloClient from 'apollo-client';
import Link from 'react-router-dom';
import gql from 'graphql-tag';
import setContext from 'apollo-link-context';
import InMemoryCache from 'apollo-cache-inmemory';
【问题讨论】:
【参考方案1】:我有同样的错误,通过使用这组库修复它
import ApolloClient from "apollo-client";
import createHttpLink from "apollo-link-http";
import setContext from "apollo-link-context";
import InMemoryCache from "apollo-cache-inmemory";
【讨论】:
以上是关于React 和 ApolloClient:网络错误:forward(...).subscribe 不是函数的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Apollo Client 上自动从网络错误中恢复?
未处理的拒绝(错误):渲染的钩子比上一次渲染时更多(React Interface GrandStack with ApolloClient)
Android 设备上的 Apollo 网络错误(React Native)
使用 expo start 启动时,Expo 不会创建 Websocket ApolloClient 实例