This is a very common problem, and the answers given here aren't correctactually.
Unity Unity provides SetSizeWithCurrentAnchorsSetSizeWithCurrentAnchors() for setting either width or height, ignoring the current anchors (which is almost certainly what you want)
https://docs.unity3d.com/ScriptReference/RectTransform.SetSizeWithCurrentAnchors.html.