首页 > 解决方案 > typeError:无法在“ResizeObserver”上执行“观察”:参数 1 不是“元素”类型

问题描述

为了解释上下文,我正在为一个 gatsby 项目构建一个 instagram 轮播。轮播中的图像显示为

                  {data.allInstaNode.edges.map((image) => (
                        <Background
                            src={image.node.localFile.childImageSharp.fluid}
                            className="img-fluid"
                            height="38vh"
                            width="100%"
                        />
                    ))}

渲染图像的背景组件使用 Gatsby 背景图像,如下所示

import React from 'react';
import BackgroundImage from 'gatsby-background-image';

export default function Background(props) {
    return (
        <BackgroundImage
            xs={props.xs}
            sm={props.sm}
            md={props.md}
            lg={props.lg}
            fluid={props.src}
            style={{ height: `${props.height}`, width: `${props.width}`, margin: '1rem' }}
        >
            {props.children}
        </BackgroundImage>
    );
}

这个问题是这个内容过去渲染得很好,现在没有这样做,因为它给了我这个错误-TypeError:无法在'ResizeObserver'上执行'observe':参数1不是'Element'类型。

我做了一些搜索来解决这个问题并遇到了这个似乎很有希望但对我来说不是很清楚的解决方案 - https://github.com/souporserious/react-measure/issues/76

任何人都可以帮忙吗?:)

标签: javascriptreactjsgatsby

解决方案


发生这种情况是因为在您尝试引用它时该元素尚不存在。

您可以使用setTimeout(() => { yourCode },100)它在尝试访问 dom 元素之前等待 100 毫秒,或者您可以使用

await waitUntil(() => myDomElement != null, { timeout: 20000 });
.... <your code> 

这将在运行代码之前等待您的元素不为空(上面的代码将等待长达 20 秒,超时以毫秒为单位)


推荐阅读