开发者问题收集

Gatsby,Stripe:创建按钮源代码返回“未捕获的 TypeError:无法读取未定义的属性‘configure’”

2018-10-18
834

我正在根据 此处 的教程条目构建电子商务网站。

但是,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)

我看到很多 Uncaught TypeError: Cannot read property 'configure' of undefined 和 404 错误。

尝试使用 CSS-in-JS 库和 styled-components 进行编写,因为我在这个项目中使用了它。 不同之处在于,现在显示的图标和之前教程中完全相同的源代码甚至都没有显示图标。

错误消息变成了这样。

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

相关信息:

此外,我测试了使用教程中完全相同的代码制作 index.js,但结果与上面的相同。 当我禁用 checkout.js 组件时,它运行良好,这意味着我敢打赌 checkout.js 代码最有可能被修复。

src/components/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

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
2个回答

错误 Uncaught TypeError: Cannot read property 'configure' of undefined 表示您没有加载 StripeCheckout

按照您正在遵循的教程建议,将 stripe checkout 脚本添加到您的文档中。

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

您可以将其放在 html 文档的 <head> 中,或者放在结束​​ </html> 标签的正下方。


此外,您可以改用 https://github.com/stripe/react-stripe-elements ,它允许您在 package.json 中管理依赖项并在代码中 import 它。

它的用法略有不同,但它们的文档非常精彩。

Seth
2018-10-18

问题发生在构建期间,因为此代码段第 2 行中的“window”不是有效对象:

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

当 Gatsby 为您的网站构建静态资产时,“window”不存在。当您运行 Gatsby servegastby build 或部署到 Netlify(或任何地方)时,就会发生这种情况。

为了避免在构建期间出现此问题,请将该行包装在 if 语句中以检查 window 是否存在。

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

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

dns
2019-01-04