简体   繁体   English

Gatsby、Stripe:创建按钮源代码返回“未捕获的类型错误:无法读取未定义的属性‘配置’”

[英]Gatsby, Stripe: Creating a button source code returns 'Uncaught TypeError: Cannot read property 'configure' of undefined'

I'm building an e-commerce site based on a tutorial entry from here .我正在根据此处的教程条目构建电子商务网站。

But, from a source code for checkout.js returns these errors and the entire page is all white out.但是,从 checkout.js 的源代码返回这些错误,整个页面都是白色的。

Uncaught TypeError: Cannot read property 'configure' of undefined
The above error occurred in the <Checkout> component:
The above error occurred in the <LocationProvider> component:
GET http://localhost:8000/.../src/components/checkout.js 404 (Not Found)

I see lots of Uncaught TypeError: Cannot read property 'configure' of undefined and 404 error the most.我看到很多Uncaught TypeError: Cannot read property 'configure' of undefined和 404 错误最多。

Tried to see with writing CSS-in-JS library, styled-components because I use for this project.试图通过编写 CSS-in-JS 库和 styled-components 来查看,因为我用于这个项目。 A difference is, favicon shows and before with all exactly same source code from a tutorial was not even showing favicon.不同之处在于,网站图标显示和之前教程中所有完全相同的源代码甚至没有显示网站图标。

An error message changed into this.一条错误信息变成了这个。

Uncaught Error: Thestyleprop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.

Relevant information:相关信息:

Also, I tested with making index.js with exactly same code in tutorial, but the results are the same as in above.另外,我在教程中使用完全相同的代码制作 index.js 进行了测试,但结果与上面相同。 When I disable checkout.js component, it works perfectly, means I bet checkout.js code has the highest potential to be fixed.当我禁用 checkout.js 组件时,它可以完美运行,这意味着我敢打赌 checkout.js 代码最有可能被修复。

src/components/checkout.js源代码/组件/checkout.js

import React from "react"

// hardcoded amount (in US cents) to charge users
// you could set this variable dynamically to charge different amounts
const amount = 2500
const cardStyles = {
  display: "flex",
  flexDirection: "column",
  justifyContent: "space-around",
  alignItems: "flex-start",
  padding: "3rem",
  boxShadow: "5px 5px 25px 0 rgba(46,61,73,.2)",
  backgroundColor: "#fff",
  borderRadius: "6px",
  maxWidth: "400px",
}
const buttonStyles = {
  fontSize: "13px",
  textAlign: "center",
  color: "#fff",
  outline: "none",
  padding: "12px 60px",
  boxShadow: "2px 5px 10px rgba(0,0,0,.1)",
  backgroundColor: "rgb(255, 178, 56)",
  borderRadius: "6px",
  letterSpacing: "1.5px",
}

// Below is where the checkout component is defined.
// It has several functions and some default state variables.
const Checkout = class extends React.Component {
  state = {
    disabled: false,
    buttonText: "BUY NOW",
    paymentMessage: "",
  }

  resetButton() {
    this.setState({ disabled: false, buttonText: "BUY NOW" })
  }

  componentDidMount() {
    this.stripeHandler = window.StripeCheckout.configure({
      // You’ll need to add your own Stripe public key to the `checkout.js` file.
      // key: 'pk_test_STRIPE_PUBLISHABLE_KEY',
      key: "pk_test_testtesttesttesttesttest",
      closed: () => {
        this.resetButton()
      },
    })
  }

  openStripeCheckout(event) {
    event.preventDefault()
    this.setState({ disabled: true, buttonText: "WAITING..." })
    this.stripeHandler.open({
      name: "Demo Product",
      amount: amount,
      description: "A product well worth your time",
      token: token => {
        fetch(`AWS_LAMBDA_URL`, {
          method: "POST",
          mode: "no-cors",
          body: JSON.stringify({
            token,
            amount,
          }),
          headers: new Headers({
            "Content-Type": "application/json",
          }),
        })
          .then(res => {
            console.log("Transaction processed successfully")
            this.resetButton()
            this.setState({ paymentMessage: "Payment Successful!" })
            return res
          })
          .catch(error => {
            console.error("Error:", error)
            this.setState({ paymentMessage: "Payment Failed" })
          })
      },
    })
  }

  render() {
    return (
      <div style={cardStyles}>
        <h4>Spend your Money!</h4>
        <p>
          Use any email, 4242 4242 4242 4242 as the credit card number, any 3
          digit number, and any future date of expiration.
        </p>
        <button
          style={buttonStyles}
          onClick={event => this.openStripeCheckout(event)}
          disabled={this.state.disabled}
        >
          {this.state.buttonText}
        </button>
        {this.state.paymentMessage}
      </div>
    )
  }
}

export default Checkout

pages/index.js页面/index.js

import React from "react"
import Helmet from "react-helmet"
import Favicon from "../components/fav-nma.png"
import Container from "../components/container"
import Layout from "../components/layout"
import Top from "../components/top"
//import Mainbody from "../components/mainbody"
import Apply from "../components/apply"
import Checkout from "../components/checkout"
import Price from "../components/price"
import Footer from "../components/footer"

const IndexPage = () => (
  <Layout>
    <Helmet link={[
      { rel: 'shortcut icon', type: 'image/png', href: `${Favicon}` }
  ]}>
      <meta property="og:type" content="website" />
      <meta property="og:url" content="test" />
      <meta property="og:title" content="test" />
      <meta property="og:description" content="test" />
      <meta property="og:image" content="test" />
      <meta property="fb:app_id" content="test" />
      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:title" content="test" />
      <meta name="twitter:description" content="test" />
      <meta name="twitter:image" content="test" />
    </Helmet>
    <Container>
      <Top />
      <Apply />
      <div>
        <Checkout />
      </div>
      <Price />
      <Footer />
    </Container>
  </Layout>
)

export default IndexPage

The error Uncaught TypeError: Cannot read property 'configure' of undefined indicates that you didn't load StripeCheckout .错误Uncaught TypeError: Cannot read property 'configure' of undefined表示您没有加载StripeCheckout

As the tutorial that you are following suggests, add the stripe checkout script to your document.正如您所遵循的教程所建议的那样,将条带结帐脚本添加到您的文档中。

<script src="https://checkout.stripe.com/checkout.js"></script>

You can place this in the <head> of your html document or right below the closing </html> tag.您可以将其放在 html 文档的<head>中或结束</html>标记的正下方。


Additionally, you can use https://github.com/stripe/react-stripe-elements instead which allows you to manage the dependency within your package.json and import it within your code.此外,您可以使用https://github.com/stripe/react-stripe-elements代替,它允许您管理 package.json 中的依赖项并将其import到您的代码中。

Its usage is slightly different, but their documentation is fantastic.它的用法略有不同,但他们的文档非常棒。

The problem occurs during build because 'window' is not a valid object in line 2 of this snippet:问题发生在构建过程中,因为“window”不是此代码段第 2 行中的有效对象:

componentDidMount() {
  this.stripeHandler = window.StripeCheckout.configure({
    key: "pk_test_testtesttesttesttesttest",
    closed: () => {
      this.resetButton()
    },
  })
}

'window' doesn't exist while Gatsby builds the static assets for your site.当 Gatsby 为您的站点构建静态资产时,“窗口”不存在。 This occurs when you run Gatsby serve or gastby build or when you deploy to Netlify (or wherever).当您运行Gatsby servegastby build或部署到 Netlify(或任何地方)时,就会发生这种情况。

To avoid this problem during build, wrap that line in an if statement to check whether window exists.为避免在构建期间出现此问题,请将该行包装在 if 语句中以检查window是否存在。

componentDidMount() {
  if (typeof window !== `undefined`) {
    this.stripeHandler = window.StripeCheckout.configure({
      key: `pk_test_testtesttesttesttesttest`,
      closed: () => {
        this.resetButton()
      }
    })
  }
}

I stole this info from: https://www.gatsbyjs.org/docs/debugging-html-builds/我从以下位置窃取了此信息: https : //www.gatsbyjs.org/docs/debugging-html-builds/

暂无
暂无

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

相关问题 未捕获的TypeError:无法使用Gatsby和graphQl读取未定义的属性“数据” - Uncaught TypeError: Cannot read property 'data' of undefined with Gatsby and graphQl 带有 Electron 的 TestCafe 抛出“Uncaught TypeError: Cannot read property 'source' of undefined” - TestCafe with Electron throwing "Uncaught TypeError: Cannot read property 'source' of undefined" toDataURL返回错误“未捕获的TypeError:无法读取未定义的属性&#39;0&#39;” - toDataURL returns error “Uncaught TypeError: Cannot read property '0' of undefined ” GATSBY:类型错误:无法读取未定义的属性“包含” - GATSBY: TypeError: Cannot read property 'includes' of undefined Gatsby TypeError:无法读取未定义的属性“allWordpressAcfOptions” - Gatsby TypeError: Cannot read property 'allWordpressAcfOptions' of undefined 未捕获的类型错误:创建标记时无法读取未定义的属性“createIcon” - Uncaught TypeError: Cannot read property 'createIcon' of undefined when creating markers 未捕获的类型错误:无法通过创建图表来读取未定义的属性“名字” - Uncaught TypeError: Cannot read property 'firstname' of undefined by creating a graph 多个按钮事件 = 未捕获的类型错误:无法读取未定义的属性“删除” - Multiple Button events = Uncaught TypeError: Cannot read property 'remove' of undefined 未捕获的TypeError:无法读取未定义的属性“未定义” - Uncaught TypeError: Cannot read property 'undefined' of undefined 未捕获的类型错误:无法使用 Electron 更新程序代码读取未定义的属性“on” - Uncaught TypeError: Cannot read property 'on' of undefined with Electron updater code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM