简体   繁体   English

React/Node 应用程序无法在 Chrome 上运行“错误运行模板:不变违规:无效的挂钩调用”

[英]React/Node app not working on Chrome “Error running template: Invariant Violation: Invalid hook call”

I am getting an error in my react/node/meteor application.我的 react/node/meteor 应用程序出现错误。 In particular, the app fails to load on Chrome, but works properly on all other browsers (edge, firefox).特别是,该应用无法在 Chrome 上加载,但在所有其他浏览器(edge、firefox)上都能正常运行。 On Chrome I get a 500 error and the page does not load.在 Chrome 上,我收到 500 错误并且页面无法加载。 On the terminal, where I am running the app, I get this:在我运行应用程序的终端上,我得到了这个:

   (webapp_server.js:1010) Error running template: Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks...

I know that there are three common causes of this error as we see here:我知道这个错误有三个常见的原因,正如我们在这里看到的:

https://reactjs.org/warnings/invalid-hook-call-warning.html https://reactjs.org/warnings/invalid-hook-call-warning.html

But I am using "react": "^16.8.0", "react-dom": "^16.8.0", and I don't use react native.但我使用的是“react”:“^16.8.0”,“react-dom”:“^16.8.0”,我不使用 react native。

I don't believe I am improperly using hooks.我不相信我不正确地使用了钩子。

I ran this: meteor npm ls react我跑了这个: meteor npm ls反应

and got back the following response: `-- react@16.8.6并得到以下回复:`-- react@16.8.6

I have reset my machine and still the problem persists: Edge works fine, Chrome fails to load.我已经重置了我的机器,但问题仍然存在:Edge 工作正常,Chrome 无法加载。

Here is the code that is having the error:这是出现错误的代码:

import React from 'react';
import MeteorLoadable from 'meteor/nemms:meteor-react-loadable';
import acceptLanguage from 'accept-language';
import { renderToString } from 'react-dom/server';
import { ServerStyleSheet } from 'styled-components';
import { Meteor } from 'meteor/meteor';
import { onPageLoad } from 'meteor/server-render';
import { ApolloClient } from 'apollo-client';
import { ApolloProvider, getDataFromTree } from 'react-apollo';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { StaticRouter, Route } from 'react-router-dom';
import Helmet from 'react-helmet';
import fetch from 'node-fetch';

import App from '/app/ui/components/smart/app';
import HeaderTitle from '/app/ui/components/smart/header/header-title';
import LanguagePicker from '/app/ui/components/dumb/language-picker';
import Routes from '/app/ui/routes';
import { primaryLocale, otherLocales } from '/app/intl';

const locales = primaryLocale ? [primaryLocale, ...otherLocales] : otherLocales;
acceptLanguage.languages(locales);

const render = async (sink) => {
  const ssrClient = new ApolloClient({
    link: new HttpLink({
      uri: Meteor.absoluteUrl('/graphql'),
      fetch,
    }),
    cache: new InMemoryCache(),
    ssrMode: true,
  });

  const preferredLocale = acceptLanguage.get(sink.request.headers['accept-language']);
  let locale = otherLocales.find(l => sink.request.url.path.startsWith(`/${l}`));
  let prefix = locale;

  // /app-shell is a special route that does no server-side rendering
  // It's used by the service worker for all navigation routes, so after the first visit
  // the initial server response is very quick to display the app shell, and the client
  // adds in the data.

  // In the case of a first visit or a robot, we render everything on the server.
  if (sink.request.url.path === '/app-shell') {
    sink.appendToBody(`<script>window.__APOLLO_STATE__=${JSON.stringify(ssrClient.extract())};</script>`);
    sink.appendToBody(`<script>window.__PREFERRED_LOCALE__='${preferredLocale}';</script>`);
    sink.appendToBody(MeteorLoadable.getLoadedModulesScriptTag());
    return;
  }

  // We first check if we need to redirect to a locale
  // We can only do this is there isn't a primary locale.
  if (!primaryLocale) {
    if (!locale) {
      sink.setStatusCode(307);
      sink.redirect(`/${preferredLocale || otherLocales[0]}${sink.request.url.path}`);
      return;
    }
  } else if (!locale) {
    // If there's no locale prefix, we use the primaryLocale instead
    locale = primaryLocale;
    prefix = '';
  }

  const ServerApp = ({ component, context }) => (
    <MeteorLoadable.Capture>
      <StaticRouter location={sink.request.url} context={context}>
        <ApolloProvider client={ssrClient}>
          <Route
            path={`/${prefix}`}
            render={props => <App component={component} {...props} locale={locale} section="app" />}
          />
        </ApolloProvider>
      </StaticRouter>
    </MeteorLoadable.Capture>
  );

  // Load all data from local server
  const context = {};
  await getDataFromTree(<ServerApp component={Routes} context={context} />);

  // Elements that we want rendered on the server
  const sheet = new ServerStyleSheet();
  sink.renderIntoElementById('header-title', renderToString(sheet.collectStyles(<ServerApp component={HeaderTitle} context={context} />)));
  sink.renderIntoElementById('header-lang-picker', renderToString(sheet.collectStyles(<ServerApp component={LanguagePicker} context={context} />)));
  sink.renderIntoElementById('main', renderToString(sheet.collectStyles(<ServerApp component={Routes} context={context} />)));

  // Append helmet and styles
  const helmetResult = Helmet.renderStatic();
  ['title', 'meta', 'link', 'script'].forEach(k => sink.appendToHead(helmetResult[k].toString()));
  sink.appendToHead(sheet.getStyleTags());

  // Append user's preferred locale
  sink.appendToBody(`<script>window.__PREFERRED_LOCALE__='${preferredLocale}';</script>`);

  // Append Apollo data
  sink.appendToBody(`<script>window.__APOLLO_STATE__=${JSON.stringify(ssrClient.extract())};</script>`);

  // Append preloaded ReactLoadabe modules
  sink.appendToBody(MeteorLoadable.getLoadedModulesScriptTag());
};

Meteor.startup(async () => {
  await MeteorLoadable.preloadComponents();
  onPageLoad(render);
});

In particular it is this line that is returning the error:特别是返回错误的是这一行:

await getDataFromTree(<ServerApp component={Routes} context={context} />);

I commented that line out and the app seems to work fine now.我评论了这条线,该应用程序现在似乎运行良好。 I don't know if I need it and it should not be causing problems.我不知道我是否需要它,它不应该引起问题。 This code is copied line for line from a starter kit and I don't know what this code is doing.此代码是从入门工具包中逐行复制的,我不知道此代码在做什么。

Note: This code is taken from the following starter kit:注意:此代码取自以下入门工具包:

https://github.com/timothyarmes/ta-meteor-apollo-starter-kithttps://github.com/timothyarmes/ta-meteor-apollo-starter-kit

It looks like this did disobey hooks and so I changed the following code:看起来这确实违反了钩子,所以我更改了以下代码:

  await getDataFromTree(<ServerApp component={Routes} context={context} />);

To this:对此:

  const aServerApp = () => (
    <ServerApp component={Routes} context={context} />
  );
  await getDataFromTree(aServerApp);  

and it seems to work fine.它似乎工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Invariant Violation Invalid hook call 在部署时出错 - Invariant Violation Invalid hook call error on deployment Invariant Violation Invalid hook call / cross-origin error - Invariant Violation Invalid hook call / cross-origin error react.js - react-alert - 未捕获的不变违规:无效的钩子调用 - react.js - react-alert - Uncaught Invariant Violation: Invalid hook call 未捕获的不变违规:无效的挂钩调用。 React类实现中的问题 - Uncaught Invariant Violation: Invalid hook call. Problem in React Class Implementation 从自定义 React 组件库导入和使用组件会导致 Invariant Violation: Invalid hook call - Importing and using component from custom React Component Library results in Invariant Violation: Invalid hook call 在 React Native 中使用 react-navigation v6 的 Auth Flow 出现问题。 错误:无效的挂钩调用。 不变违规:“main”尚未注册 - Issue with Auth Flow using react-navigation v6 in React Native. Error: Invalid hook call. Invariant Violation: "main" has not been registered 反应本机错误-违反常态:元素类型无效 - React Native Error - Invariant Violation: Element type is invalid 未捕获的错误:不变违规:React.render():无效的组件元素 - Uncaught Error: Invariant Violation: React.render(): Invalid component element React Error - Uncaught Invariant Violation:元素类型无效 - React Error - Uncaught Invariant Violation: Element type is invalid 重新安装节点模块后 React App 中的无效挂钩调用错误 - Invalid hook call error in React App after re-installing node modules
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM