Actually, there is an elementary proof of this. I will imitate the one given in O.Forster Lectures on Riemann Surfaces. We assume $M$ is connected. Let $Y$ be equal to the union of $X$ with all the relatively compact components of $M \setminus X$

Let $U$ be a relatively compact, open subset containing $X$ and let $C_j$, $j \in J$ be the connected components of $M \smallsetminus X$. Let $bU$ be the boundary of $U$, which is compact and disjoint from $X$.

- Claim 1. Every $C_j$ meets $U$: If $C_j \subset M \setminus U$, its closure in $M$ is also contained in $M \setminus U$, but $C_j$ is a connected component of $M \setminus U$ so $C_j = \overline{C_j}$ which conttradicts connectedness of $M$.
- Claim 2. Only finitely many $C_j$ intersects $bU$: This is because $bU$ is compact and the $C_j$ are open and disjoint, anc cover $bU$.
- Claim 3. $Y$ is closed: Let $J_0$ consist of the indices corresponding to relatively compact components. Then $M \setminus Y = \bigcup_{j \not \in J_0} C_j$, which is open.

By Claim 2, we can find $j_1, \ldots , j_k \in J_0$ be such that $C_{j_i}$ intersects $bU$. Then , by Claim 1 again, any other $C_j$ is contained in $U$. Therefore,
$$ Y \subset U \cup C_{j_1} \cup \ldots \cup C_{j_k}$$
RHS is relatively compact by the choice of $U$ and the $j_i$, and LHS is closed by Claim 3, so LHS is compact too.