ReferenceError: self is not defined using React-Pixi and Next-urql

ReferenceError: self is not defined using React-Pixi and Next-urql

我在使用 Next-Urql 和 React-Pixi 时不断收到此错误。我理解这是因为 React-Pixi 需要 WEB API。

Server Error

ReferenceError: self is not defined This error happened while generating the page. Any console logs will be displayed in the terminal window.

这是我的代码:

import { Graphics, Stage } from "@inlet/react-pixi";
import { withUrqlClient } from "next-urql";
import { createUrqlClient } from "../../../utils/urqlUtils/createUrqlClient";
import NoSSR from "react-no-ssr";
const edit = () => {
....
  
  return (
    <Layout metaTags={metaTags}>
      <Flex flexDir="row">
            {typeof window !== "undefined" && (
          <NoSSR>

              <Stage>
                <Graphics
                  draw={(g) => {
                    g.beginFill(0xff3300);
                    g.lineStyle(4, 0xffd900, 1);

                    g.moveTo(50, 50);
                    g.lineTo(250, 50);
                    g.lineTo(100, 100);
                    g.lineTo(50, 50);
                    g.endFill();

                    g.lineStyle(2, 0x0000ff, 1);
                    g.beginFill(0xff700b, 1);
                    g.drawRect(50, 250, 120, 120);

                    g.lineStyle(2, 0xff00ff, 1);
                    g.beginFill(0xff00bb, 0.25);
                    g.drawRoundedRect(150, 450, 300, 100, 15);
                    g.endFill();

                    g.lineStyle(0);
                    g.beginFill(0xffff0b, 0.5);
                    g.drawCircle(470, 90, 60);
                    g.endFill();
                  }}
                />
              </Stage>
              </NoSSR>
            )}
          </Flex>
    </Layout>
  );
};

export default withUrqlClient(createUrqlClient, { ssr: false })(edit);

我知道我应该使用动态渲染,但是当我这样做时,我总是出错。

我猜你在使用 Next.js 说 self 它在服务器端不可用 globalThis MDN

您可以在 react pixi repo. Supposedly, you can try import no SSR Next.js 上找到相关问题。

// Separate your pixi into a component and import
import dynamic from 'next/dynamic'

const PixiComponentWithNoSSR = dynamic(
  () => import('../components/your-pixi-component'),
  { ssr: false }
)

return (
  ...
    <PixiComponentWithNoSSR />
  ...
)